Exemple #1
0
        private void clearReferences(DBNode <T> node)
        {
            if (node == null)
            {
                return;
            }

            if (treeNodeLookup.ContainsKey(node))
            {
                treeNodeLookup.Remove(node);
            }

            if (watchedNodes.Contains(node))
            {
                watchedNodes.Remove(node);
            }

            if (node.Children != null)
            {
                foreach (DBNode <T> childNode in node.Children)
                {
                    clearReferences(childNode);
                }
            }
        }
Exemple #2
0
        private void removeNode()
        {
            if (treeView.SelectedNode != null)
            {
                DBNode <T> selectedNode = treeView.SelectedNode.Tag as DBNode <T>;
                if (selectedNode == null || selectedNode.AutoGenerated)
                {
                    return;
                }

                if (treeView.SelectedNode.Parent == null)
                {
                    _menu.RootNodes.Remove(selectedNode);
                    treeView.Nodes.Remove(treeView.SelectedNode);
                }
                else
                {
                    ((DBNode <T>)treeView.SelectedNode.Parent.Tag).Children.Remove(selectedNode);
                    setVisualProperties(treeView.SelectedNode.Parent);
                    updateFilteredItems(treeView.SelectedNode.Parent, false);
                }


                clearReferences(selectedNode);
                selectedNode.Delete();
            }
        }
Exemple #3
0
        private void addDynamicNode(DBField field, DBRelation relation, bool forceRoot)
        {
            if (_menu == null)
            {
                return;
            }

            SuspendLayout();

            // build internal node object
            DBNode <T> newNode = new DBNode <T>();

            newNode.Name = field.FriendlyName;
            newNode.BasicFilteringField    = field;
            newNode.BasicFilteringRelation = relation;
            newNode.DynamicNode            = true;
            newNode.DBManager = DBManager;

            count++;

            // build treenode object (for the UI)
            asyncInput       = newNode;
            forceNewNodeRoot = forceRoot;
            ProgressPopup p = new ProgressPopup(new WorkerDelegate(createTreeNodeAsyncWorker));

            p.Owner         = FindForm();
            p.Text          = "Building Menu Tree";
            p.WorkComplete += new WorkCompleteDelegate(addDynamicNode_TreeNodeCreated);
            p.ShowDialogDelayed(300);
        }
Exemple #4
0
        private void addNodeButton_Click(object sender, EventArgs e)
        {
            AddNodePopup popup = new AddNodePopup();

            popup.Table = typeof(T);

            DBNode <T> node = null;

            if (treeView.SelectedNode != null && treeView.SelectedNode.Tag is DBNode <T> )
            {
                node = (DBNode <T>)treeView.SelectedNode.Tag;
            }
            if (node == null || node.DynamicNode)
            {
                popup.ForceTopLevel = true;
            }

            popup.ShowDialog();

            if (popup.CloseState == AddNodePopup.CloseStateEnum.ADD_BASIC)
            {
                addEmptyNode(popup.AddToRoot);
            }
            else if (popup.CloseState == AddNodePopup.CloseStateEnum.ADD_DYNAMIC)
            {
                addDynamicNode(popup.DynamicFilteringField, popup.DynamicFilteringRelation, popup.AddToRoot);
            }
        }
Exemple #5
0
        private void updateButtonStates()
        {
            DBNode <T> node = null;

            if (treeView.SelectedNode.Tag is DBNode <T> )
            {
                node = (DBNode <T>)treeView.SelectedNode.Tag;
            }

            if (node == null || node.AutoGenerated)
            {
                addNodeButton.Enabled    = false;
                removeNodeButton.Enabled = false;
                convertToRegularMenuItemButton.Enabled = false;
            }
            else if (node.DynamicNode)
            {
                addNodeButton.Enabled    = true;
                removeNodeButton.Enabled = true;
                convertToRegularMenuItemButton.Enabled = true;
            }
            else
            {
                addNodeButton.Enabled    = true;
                removeNodeButton.Enabled = true;
                convertToRegularMenuItemButton.Enabled = false;
            }
        }
    public void CombinationStageCompileDeps(int level, DBNode node, ArrayList deps)
    {
        if (node == null)
        {
            return;
        }

        if (node.Type == DBNode.NodeType.Dependency &&
            node.Level == level &&
            node.IsGoal == false)
        {
            if (deps.Contains(node.State))
            {
                return;
            }

            /*if (deps.Contains (node.State))
             *      throw (new ArgumentException ("Invalid tree supplied"));*/

            deps.Add(node.State);

            // We do not need to look below.
            return;
        }

        foreach (DBNode child in node.Children)
        {
            CombinationStageCompileDeps(level, child, deps);
        }
    }
Exemple #7
0
        private void convertToRegularMenuItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView.SelectedNode == null || !(treeView.SelectedNode.Tag is DBNode <T>))
            {
                return;
            }

            DBNode <T> node = treeView.SelectedNode.Tag as DBNode <T>;

            if (!node.DynamicNode)
            {
                return;
            }

            DialogResult result = MessageBox.Show("This will permanently change this dynamic menu item\n" +
                                                  "to a standard menu item. This means sub elements will no\n" +
                                                  "longer be automatically generated. This also means you\n" +
                                                  "can manually modify the menu items.\n\n" +
                                                  "Do you want to continue?", "Change to Normal Menu Item?", MessageBoxButtons.YesNo);

            if (result == DialogResult.No)
            {
                return;
            }

            node.DynamicNode = false;
            setVisualProperties(treeNodeLookup[node]);

            foreach (DBNode <T> currSubNode in node.Children)
            {
                currSubNode.AutoGenerated = false;
                setVisualProperties(treeNodeLookup[currSubNode]);
            }
        }
    private static void GoalPathesI(GBSearchModule module,
                                    ArrayList goalpathes, DBNode node, Stack path)
    {
        if (node == null)
        {
            return;
        }

        if (module.IsGoal(node.State))
        {
            ArrayList newGoalPath = new ArrayList();

            foreach (DBNode pNode in path)
            {
                newGoalPath.Add(pNode);
            }

            newGoalPath.Reverse();

            newGoalPath.Add(node);
            goalpathes.Add(newGoalPath);

            return;
        }

        foreach (DBNode child in node.Children)
        {
            path.Push(node);
            GoalPathesI(module, goalpathes, child, path);
            path.Pop();
        }
    }
Exemple #9
0
    /// <summary>
    /// 根据元素位置得到指定的节点
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    private DBNode <T> GetNodeAt(int index)
    {
        if (IsEmpty())
        {
            LogTool.Log(string.Format("链表为空"), LogEnum.NormalLog);
            return(null);
        }

        var ptr = new DBNode <T>();

        ptr = this.Head;

        if (0 == index)
        {
            return(ptr);
        }

        var j = 0;

        while (ptr.Next != null && j < index)
        {
            j++;
            ptr = ptr.Next;
        }

        if (j == index)
        {
            return(ptr);
        }
        else
        {
            LogTool.Log(string.Format("节点并不存在"), LogEnum.NormalLog);
            return(null);
        }
    }
    private static void GoalPathI(ArrayList goalpath,
                                  DBNode node, DBNode goal, Stack path)
    {
        //Console.WriteLine ("GoalPathI");
        if (node == null)
        {
            return;
        }

        if (node == goal)
        {
            foreach (DBNode pNode in path)
            {
                goalpath.Add(pNode);
            }

            goalpath.Reverse();
            goalpath.Add(node);

            return;
        }

        foreach (DBNode child in node.Children)
        {
            path.Push(node);
            GoalPathI(goalpath, child, goal, path);
            path.Pop();
        }
    }
    public bool Applicable(IDBOperator oper, DBNode node)
    {
        GBOperator   goper  = (GBOperator)oper;
        GBSpaceState gstate = (GBSpaceState)node.State;

        return(goper.Applicable(gstate));
    }
Exemple #12
0
    private DBNode <T> GetItemAt(int index)
    {
        //判空
        if (IsEmpty())
        {
            LogTool.Log(string.Format("链表为空"), LogEnum.NormalLog);
            return(null);
        }

        var ptr = new DBNode <T>();

        ptr = Head;

        // 如果是第一个node
        if (0 == index)
        {
            return(ptr);
        }

        var j = 0;

        while (ptr.Next != null && j < index)
        {
            j++;
            ptr = ptr.Next;
            if (j == index)
            {
                return(ptr);
            }
        }

        LogTool.Log(string.Format("节点并不存在"), LogEnum.NormalLog);
        return(null);
    }
        public static void CreateMovingPictureCategories()
        {
            if (!TraktSettings.MovingPicturesCategories)
                return;

            TraktLogger.Debug("Checking if Category has already been created");
            if (TraktSettings.MovingPicturesCategoryId == -1)
            {
                TraktLogger.Debug("Category not created so let's create it");
                DBNode<DBMovieInfo> traktNode = new DBNode<DBMovieInfo>();
                traktNode.Name = "${Trakt}";

                DBMovieNodeSettings nodeSettings = new DBMovieNodeSettings();
                traktNode.AdditionalSettings = nodeSettings;

                TraktLogger.Debug("Setting the sort position to {0}", (MovingPicturesCore.Settings.CategoriesMenu.RootNodes.Count + 1).ToString());
                //Add it at the end
                traktNode.SortPosition = MovingPicturesCore.Settings.CategoriesMenu.RootNodes.Count + 1;

                TraktLogger.Debug("Adding to Root Node");
                MovingPicturesCore.Settings.CategoriesMenu.RootNodes.Add(traktNode);

                TraktLogger.Debug("Committing");
                MovingPicturesCore.Settings.CategoriesMenu.Commit();

                TraktLogger.Debug("Saving the ID {0}", traktNode.ID.ToString());
                TraktSettings.MovingPicturesCategoryId = (int)traktNode.ID;
                TraktSettings.saveSettings();

            }
            else
            {
                TraktLogger.Debug("Category has already been created");
            }
        }
Exemple #14
0
        private void modify(Func <DBVertice, bool> handler)
        {
            Document        doc       = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DBEntityControl dbControl = Project.Instance.GetTmpEntCol(doc);
            DBEntity        entity    = dbControl.FindOne
                                            (Query.EQ("HandleValue", this._handleValue));

            if (entity == null)
            {
                return;
            }

            bool changed = false;

            if (entity.Type == "Tunnel")
            {
                DBTunnel tunnel = entity as DBTunnel;
                changed = handler(tunnel.BasePoints[this._index]);
            }
            else if (entity.Type == "TunnelNode")
            {
                DBNode node = entity as DBNode;
                changed = handler(node.Position);
            }
            if (changed)
            {
                dbControl.Update(entity, Project.Instance.GetActivePropCtl(doc));
            }
        }
Exemple #15
0
        private void сохранитьВЖурналToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DBFile         File = new DBFile();
            SaveFileDialog svf  = new SaveFileDialog();

            svf.Filter = "BD Data|*.bd";
            if (svf.ShowDialog() == DialogResult.OK)
            {
                File.FileDB = svf.FileName;
            }
            foreach (var item in treeView1.Nodes)
            {
                var    o = item as TreeNode;
                var    d = o.Text.Substring(1, 6);
                DBNode n = new DBNode()
                {
                    FilePath   = o.Name,
                    Camera     = "Created by OtherCoder",
                    Date       = new DateTime(int.Parse(d.Substring(0, 2)), int.Parse(d.Substring(2, 2)), int.Parse(d.Substring(4))),
                    RecordTime = FFprobe.FFprobe.GetDuration(o.Name)
                };
                File.AddNode(n);
            }
            File.Save();
            MessageBox.Show("Успешно");
        }
Exemple #16
0
        /// <summary>
        /// 添加事件使临时数据库与图纸中所有效的数据相一致
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void db_ObjectAppend(object sender, ObjectEventArgs e)
        {
            if (!(e.DBObject is BaseTunnel) && !(e.DBObject is Node))
            {
                return;
            }

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            Entity entity = e.DBObject as Entity;

            if (entity == null || entity.BlockName != "*Model_Space")
            {
                return;
            }

            if (entity is BaseTunnel)
            {
                DBEntityControl dbControl = Project.Instance.GetTmpEntCol(doc);

                DBTunnel dbTunnel = new DBTunnel();
                dbTunnel.SetProperty(entity);
                dbControl.Insert(dbTunnel, db);
            }
            else if (entity is Node)
            {
                DBEntityControl dbControl = Project.Instance.GetTmpEntCol(doc);
                DBNode          dbNode    = new DBNode();
                dbNode.SetProperty(entity);
                dbControl.Insert(dbNode, db);
            }
        }
        public override bool UpdateDynamicNode(DBNode <DBMovieInfo> node)
        {
            if (node.BasicFilteringField == DBField.GetFieldByDBName(typeof(DBMovieInfo), "year"))
            {
                UpdateYear(node);
                TranslateName(node);
                return(true);
            }

            if (node.BasicFilteringField == DBField.GetFieldByDBName(typeof(DBMovieInfo), "date_added"))
            {
                UpdateDateAdded(node);
                TranslateName(node);
                return(true);
            }

            if (node.BasicFilteringField == DBField.GetFieldByDBName(typeof(DBMovieInfo), "actors"))
            {
                UpdateActors(node);
                TranslateName(node);
                return(true);
            }

            // for all other dynamic nodes, use generic processing but use a translated name
            node.UpdateDynamicNodeGeneric();
            TranslateName(node);
            return(true);
        }
Exemple #18
0
    /// <summary>
    /// 根据元素的值查找索引
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public int IndexOf(T value)
    {
        if (IsEmpty())
        {
            LogTool.Log(string.Format("链表为空"), LogEnum.NormalLog);
            return(-1);
        }

        var ptr = new DBNode <T>();

        ptr = Head;
        var index = 0;

        while (ptr.Next != null && !ptr.Data.Equals(value)) //查找value相同的item
        {
            ptr = ptr.Next;
            index++;
        }

        if (ptr.Data.Equals(value))
        {
            return(index);
        }
        else
        {
            return(-1);
        }
    }
    /** Build a list of goal pathes.
     */
    private static ArrayList GoalPathes(GBSearchModule module, DBNode root)
    {
        ArrayList goalpathes = new ArrayList();

        GoalPathesI(module, goalpathes, root, new Stack());

        return(goalpathes);
    }
    public void RegisterNewNode(DBNode node, DBNode root)
    {
        DoExpirationCheck();

        if (node.IsGoal == false)
        {
            return;
        }

        // For goal nodes, we check if on-the-fly refutation is wanted, and if
        // so, we try to refute the goal node.
        if (doDefenseRefutationCheck)
        {
            GBSpaceState     gRootState = (GBSpaceState)root.State;
            GBThreatSequence seq        = GBThreatSearch.DefenseRefutable
                                              (gRootState.GB, root, node);

            if (seq != null)
            {
                throw (new GBThreatSearch.GBWinningThreatSequenceFoundException(seq));
            }
        }

        // This is old code
#if false
        // Now the last node did modify something, but we only want to cache
        // dependency nodes, as combination nodes will not be combined
        // themselves.
        if (node.Type != DBNode.NodeType.Dependency)
        {
            return;
        }

        GBSpaceState state = (GBSpaceState)node.State;
        GBOperator   last  = state.LastOperator;
        if (last == null)
        {
            return;
        }

        // Now, we add this node to the array at all its influencing places,
        // but only where it sets a stone of the attacker (which is the only
        // position that can create new possibilities for attack).
        for (int n = 0; n < last.fAdd.GetLength(0); ++n)
        {
            // Ignore everything except the attacker stones.
            if (last.fAdd[n, 2] != 1)
            {
                continue;
            }

            // Add coordinate
            nodesThatAffectSquares[last.fAdd[n, 1], last.fAdd[n, 0]].Add(node);

            return;
        }
#endif
    }
Exemple #21
0
        /// <summary>
        /// 保存事件使数据库与图纸中的已保存数据相一致
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void db_SaveComplete(object sender, DatabaseIOEventArgs e)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            //保存树结构
            DBTreeControl treeControl = Project.Instance.GetMainTreeCol(doc);

            treeControl.StoreTree(Project.Instance.GetProjectTree(doc));

            //保存模型数据
            DBEntityControl dbControl = Project.Instance.GetMainEntCol(doc, true);

            TypedValue[]          value = { new TypedValue((int)DxfCode.Start, "TUNNEL_SQUARE,TUNNEL_CYLINDER,TUNNELNODE") };
            SelectionFilter       sf    = new SelectionFilter(value);
            PromptSelectionResult res   = ed.SelectAll(sf);

            if (res.Status != PromptStatus.OK)
            {
                dbControl.Delete(Query.All(), db);
                return;
            }
            SelectionSet SS = res.Value;

            if (SS == null)
            {
                return;
            }

            Autodesk.AutoCAD.DatabaseServices.ObjectId[] idArray = SS.GetObjectIds();

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
            using (Transaction myT = tm.StartTransaction())
            {
                //储存之前先把之前数据的删除干净
                int deleteCounts = dbControl.Delete(Query.All(), db);

                foreach (var id in idArray)
                {
                    Entity entity = (Entity)tm.GetObject(id, OpenMode.ForRead, true);
                    if (entity is BaseTunnel)
                    {
                        DBTunnel dbTunnel = new DBTunnel();
                        dbTunnel.SetProperty(entity);
                        dbControl.Insert(dbTunnel, db);
                    }
                    else if (entity is Node)
                    {
                        DBNode dbNode = new DBNode();
                        dbNode.SetProperty(entity);
                        dbControl.Insert(dbNode, db);
                    }
                }
                myT.Commit();
            }
        }
Exemple #22
0
        private void nodeModifiedWorker()
        {
            DBNode <T> node = pendingModification.Pop();

            setVisualProperties(treeNodeLookup[node]);
            updateFilteredItems(treeNodeLookup[node], false);

            finishedModification.Push(node);
        }
Exemple #23
0
        static public void ChangeSelection(object sender, SelectionSet set)
        {
            SelectedTunnels = new List <DBTunnel>();
            SelectedNodes   = new List <DBNode>();

            if (set.Count != 0)
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db  = doc.Database;
                Editor   ed  = doc.Editor;

                var ids = set.GetObjectIds();
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                Utils.TransactionControl(() =>
                {
                    Entity entity = null;
                    foreach (var id in ids)
                    {
                        entity = (Entity)tm.GetObject(id, OpenMode.ForRead, false);
                        if (entity.IsErased == true)
                        {
                            return;
                        }
                        long handleValue = entity.Handle.Value;
                        if (entity is BaseTunnel)
                        {
                            DBTunnel dbTunnel = Utils.GetEntityFromDB(handleValue) as DBTunnel;

                            if (dbTunnel == null)
                            {
                                return;
                            }
                            else
                            {
                                SelectedTunnels.Add(dbTunnel);
                            }
                        }
                        else if (entity is Node)
                        {
                            DBNode dbNode = Utils.GetEntityFromDB(handleValue) as DBNode;
                            if (dbNode == null)
                            {
                                return;
                            }
                            else
                            {
                                SelectedNodes.Add(dbNode);
                            }
                        }
                    }
                });
            }
            SelectedTunnelChanged?.Invoke(sender, SelectedTunnels);
            SelectedNodeChanged?.Invoke(sender, SelectedNodes);
        }
Exemple #24
0
        private void UpdateActors(DBNode <DBMovieInfo> node)
        {
            // get list of movies to find actors
            var movies = node.GetFilteredItems().ToList();

            // store a list of nodes to remove later
            var toRemove = node.Children.Where(n => n.AutoGenerated).ToList();

            // get actors available in all movies
            var actors = new List <string>();

            foreach (var movie in movies)
            {
                actors.AddRange(movie.Actors.ToString().Split('|'));
            }

            // remove invalid actors and sort list
            actors.RemoveAll(a => string.IsNullOrEmpty(a));
            actors.Sort();

            // now get a unique list of actors where they appear in atleast x movies
            var actorsToAdd = actors.GroupBy(a => a).Where(a => a.Count() >= MovingPicturesCore.Settings.ActorLimit).Select(a => a.Key);

            foreach (var actor in actorsToAdd)
            {
                if (!toRemove.Any(n => n.Name.Equals(actor)))
                {
                    // actor not found, add it
                    DBNode <DBMovieInfo> newSubNode = new DBNode <DBMovieInfo>();
                    newSubNode.AutoGenerated = true;
                    newSubNode.Name          = actor;

                    DBFilter <DBMovieInfo> newFilter = new DBFilter <DBMovieInfo>();
                    newFilter.Name             = actor;
                    newFilter.CriteriaGrouping = DBFilter <DBMovieInfo> .CriteriaGroupingEnum.ALL;
                    newFilter.Criteria.Add(createCriteria(node, DBCriteria <DBMovieInfo> .OperatorEnum.EQUAL, actor));

                    newSubNode.Filter             = newFilter;
                    newSubNode.AdditionalSettings = new DBMovieNodeSettings();

                    node.Children.Add(newSubNode);
                    newSubNode.Parent = node;
                }
                else
                {
                    // we want to keep the existing node so don't remove it
                    toRemove.RemoveAll(n => n.Name.Equals(actor));
                }
            }

            // remove any nodes left over with no items
            foreach (var currNode in toRemove)
            {
                node.Children.Remove(currNode);
            }
        }
Exemple #25
0
        void MenuTree_SelectedNodeChanged(IDBNode node)
        {
            DBNode <DBMovieInfo> movieNode = (DBNode <DBMovieInfo>)node;

            nodeSettingsPanel.Node = movieNode;
            if (movieNodeSettingsPanel.Visible)
            {
                movieNodeSettingsPanel.Node = movieNode;
            }
        }
    /** Build a single goal path.
     */
    public static ArrayList GoalPath(DBNode root, DBNode goalnode)
    {
        /*Console.WriteLine ("GoalPath (root = {0}, goalnode = {1})",
         *      root.DebugNN, goalnode.DebugNN);*/
        ArrayList goalpath = new ArrayList();

        GoalPathI(goalpath, root, goalnode, new Stack());

        return(goalpath);
    }
Exemple #27
0
        private DBCriteria <DBMovieInfo> createCriteria(DBNode <DBMovieInfo> node, DBCriteria <DBMovieInfo> .OperatorEnum opEnum, object value)
        {
            DBCriteria <DBMovieInfo> criteria = new DBCriteria <DBMovieInfo>();

            criteria.Field    = node.BasicFilteringField;
            criteria.Relation = node.BasicFilteringRelation;
            criteria.Operator = opEnum;
            criteria.Value    = value;
            return(criteria);
        }
Exemple #28
0
        // check if a translation exists for the given field, and if so, use that escape
        // sequence rather than the DB Field Name
        private void TranslateName(DBNode <DBMovieInfo> node)
        {
            string transString = "${" + node.BasicFilteringField.Name + "}";
            string result      = Translation.ParseString(transString);

            if (result != node.BasicFilteringField.Name)
            {
                node.Name = transString;
            }
        }
Exemple #29
0
        private void moveDownButton_Click(object sender, EventArgs e)
        {
            if (treeView.SelectedNode == null || !(treeView.SelectedNode.Tag is DBNode <T>))
            {
                return;
            }

            // grab the dbnode
            DBNode <T> node = treeView.SelectedNode.Tag as DBNode <T>;

            // and the collection it belongs to
            List <DBNode <T> > collection;

            if (node.Parent == null)
            {
                collection = _menu.RootNodes;
            }
            else
            {
                collection = node.Parent.Children;
            }

            // attempt to move the node in the collection and if successful
            // commit and reflect the change on the GUI
            if (collection.MoveDown(node, true))
            {
                if (node.Parent != null)
                {
                    node.Parent.Commit();
                }
                else
                {
                    _menu.Commit();
                }

                TreeNode treeNode = treeView.SelectedNode;

                TreeNodeCollection treeCollection;
                if (treeNode.Parent == null)
                {
                    treeCollection = treeView.Nodes;
                }
                else
                {
                    treeCollection = treeNode.Parent.Nodes;
                }

                int newIndex = treeCollection.IndexOf(treeNode) + 1;
                treeCollection.RemoveAt(newIndex - 1);
                treeCollection.Insert(newIndex, treeNode);

                treeView.SelectedNode = treeNode;
            }
        }
Exemple #30
0
    /// <summary>
    /// 打印双向链表的每个元素
    /// </summary>
    public void Print()
    {
        var current = new DBNode <T>();

        current = Head;
        LogTool.Log(string.Format(current.Data + ","), LogEnum.NormalLog);
        while (current.Next != null)
        {
            LogTool.Log(string.Format(current.Next.Data + ","), LogEnum.NormalLog);
            current = current.Next;
        }
    }
    public void CombinationStage(int level, DBNode root, DBSearch dbs)
    {
#if false
        ArrayList thisDepsStates = new ArrayList();
        CombinationStageCompileDeps(level, root, thisDepsStates);

        GBOperatorCombineFastCheck cfc =
            new GBOperatorCombineFastCheck(dbs, this, thisDepsStates, level);

        cfc.CombineCheck(nodesThatAffectSquares);
#endif
    }
    private static void GoalPathesI(GBSearchModule module,
		ArrayList goalpathes, DBNode node, Stack path)
    {
        if (node == null)
            return;

        if (module.IsGoal (node.State)) {
            ArrayList newGoalPath = new ArrayList ();

            foreach (DBNode pNode in path)
                newGoalPath.Add (pNode);

            newGoalPath.Reverse ();

            newGoalPath.Add (node);
            goalpathes.Add (newGoalPath);

            return;
        }

        foreach (DBNode child in node.Children) {
            path.Push (node);
            GoalPathesI (module, goalpathes, child, path);
            path.Pop ();
        }
    }
    /** Build a list of goal pathes.
     */
    private static ArrayList GoalPathes(GBSearchModule module, DBNode root)
    {
        ArrayList goalpathes = new ArrayList ();

        GoalPathesI (module, goalpathes, root, new Stack ());

        return (goalpathes);
    }
    /** Build a single goal path.
     */
    public static ArrayList GoalPath(DBNode root, DBNode goalnode)
    {
        /*Console.WriteLine ("GoalPath (root = {0}, goalnode = {1})",
            root.DebugNN, goalnode.DebugNN);*/
        ArrayList goalpath = new ArrayList ();

        GoalPathI (goalpath, root, goalnode, new Stack ());

        return (goalpath);
    }
        private static IEnumerable<DBNode<DBMovieInfo>> CreateNodes(IEnumerable<TraktMovie> traktRecommendationMovies, IEnumerable<TraktWatchListMovie> traktWatchListMovies)
        {
            #region WatchList
            TraktLogger.Debug("Creating the watchlist node");
            var watchlistNode = new DBNode<DBMovieInfo> {Name = "${" + GUI.Translation.WatchList + "}"};

            var watchlistSettings = new DBMovieNodeSettings();
            watchlistNode.AdditionalSettings = watchlistSettings;

            TraktLogger.Debug("Getting the Movie's from Moving Pictures");
            var movieList = DBMovieInfo.GetAll();

            TraktLogger.Debug("Creating the watchlist filter");
            var watchlistFilter = new DBFilter<DBMovieInfo>();
            foreach (var movie in traktWatchListMovies.Select(traktmovie => movieList.Find(m => m.ImdbID.CompareTo(traktmovie.Imdb) == 0)).Where(movie => movie != null))
            {
                TraktLogger.Debug("Adding {0} to watchlist", movie.Title);
                watchlistFilter.WhiteList.Add(movie);
            }

            if (watchlistFilter.WhiteList.Count == 0)
            {
                TraktLogger.Debug("Nothing in watchlist, Blacklisting everything");
                watchlistFilter.BlackList.AddRange(movieList);
            }

            watchlistNode.Filter = watchlistFilter;

            #endregion

            #region Recommendations
            TraktLogger.Debug("Creating the recommendations node");
            var recommendationsNode = new DBNode<DBMovieInfo> {Name = "${" + GUI.Translation.Recommendations + "}"};

            var recommendationsSettings = new DBMovieNodeSettings();
            recommendationsNode.AdditionalSettings = recommendationsSettings;

            TraktLogger.Debug("Creating the recommendations filter");
            var recommendationsFilter = new DBFilter<DBMovieInfo>();
            foreach (var movie in traktRecommendationMovies.Select(traktMovie => movieList.Find(m => m.ImdbID.CompareTo(traktMovie.Imdb) == 0)).Where(movie => movie != null))
            {
                TraktLogger.Debug("Adding {0} to recommendations", movie.Title);
                recommendationsFilter.WhiteList.Add(movie);
            }

            if (recommendationsFilter.WhiteList.Count == 0)
            {
                TraktLogger.Debug("Nothing in recommendation list, Blacklisting everything");
                recommendationsFilter.BlackList.AddRange(movieList);
            }

            recommendationsNode.Filter = recommendationsFilter;

            #endregion

            return new DBNode<DBMovieInfo>[] { watchlistNode, recommendationsNode };
        }
 private void addFilters(DBNode<DBMovieInfo> node)
 {
     foreach (IFilter<DBMovieInfo> currFilter in node.GetAllFilters())
         if (!Filters.Contains(currFilter))
             Filters.Add(currFilter);
 }
        /// <summary>
        /// Adds a movie criteria to a node
        /// </summary>
        /// <param name="node">Node to add movie criteria to</param>
        /// <param name="movieId">IMDb movie ID used for the criteria</param>
        static void AddMovieCriteriaToNode(DBNode<DBMovieInfo> node, string movieId)
        {
            if (node == null || !BasicHandler.IsValidImdb(movieId)) return;

            // check existing filter exists
            if (!node.HasFilter) return;

            // add movie id as a criteria
            var criteria = new DBCriteria<DBMovieInfo>();
            criteria.Field = DBField.GetFieldByDBName(typeof(DBMovieInfo), "imdb_id");
            criteria.Operator = DBCriteria<DBMovieInfo>.OperatorEnum.EQUAL;
            criteria.Value = movieId;

            // add the criteria to the filter
            node.Filter.Criteria.Add(criteria);
            node.Commit();
        }
 /// <summary>
 /// Returns a list of possible movies for this node
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public HashSet<DBMovieInfo> GetPossibleMovies(DBNode<DBMovieInfo> node)
 {
     lock (syncRefresh) {
         if (!possibleMovies.ContainsKey(node)) {
             possibleMovies[node] = node.GetPossibleFilteredItems();
         }
     }
     return possibleMovies[node];
 }
        /// <summary>
        /// Publishes category (node) related artwork to the skin
        /// </summary>
        /// <param name="node"></param>
        private void PublishArtwork(DBNode<DBMovieInfo> node)
        {
            if (node == null) {
                logger.Debug("Clearing Category Artwork");
                cover.Filename = string.Empty;
                backdrop.Filename = string.Empty;
                return;
            }

            logger.Debug("Publishing Category Artwork");

            cover.Filename = string.Empty;

            // grab the node settings
            DBMovieNodeSettings settings = node.AdditionalSettings as DBMovieNodeSettings;
            if (settings == null) {
                settings = new DBMovieNodeSettings();
                node.AdditionalSettings = settings;
            }

            // grab the backdrop
            switch (settings.BackdropType) {
                case MenuBackdropType.FILE:
                    backdrop.Filename = settings.BackdropFilePath;
                    SetProperty("#MovingPictures.Settings.BackdropMovieTitle", "");
                    break;
                case MenuBackdropType.MOVIE:
                    backdrop.Filename = settings.BackdropMovie.BackdropFullPath;
                    SetProperty("#MovingPictures.Settings.BackdropMovieTitle", settings.BackdropMovie.Title);
                    break;
                case MenuBackdropType.RANDOM:
                    DBMovieInfo movie = null;
                    HashSet<DBMovieInfo> movies = browser.GetAvailableMovies(node);
                    lock (backdropSync) {
                        // Check if this node has an active movie cached and if it's still active.
                        if (activeMovieLookup.ContainsKey(node) && movies.Contains(activeMovieLookup[node])) {
                            movie = activeMovieLookup[node];
                        } else {
                            // grab a new random movie from the visible movies that has a backdrop
                            movie = movies.Where(m => m.BackdropFullPath != null && m.BackdropFullPath.Trim().Length > 0).ToList().Random();
                            // if we found one add it to our lookup list to speed up future requests
                            if (movie != null) activeMovieLookup[node] = movie;
                        }
                    }
                    // change the backdrop or set to null
                    backdrop.Filename = (movie != null) ? movie.BackdropFullPath : null;
                    SetProperty("#MovingPictures.Settings.BackdropMovieTitle"
                        , (movie != null) ? movie.Title : null);
                    break;
            }
        }
        /// <summary>
        /// Gets a child node by name from a parent node
        /// </summary>
        /// <param name="rootNode">The parent node the child node belongs to</param>
        /// <param name="name">The name of the node to retrieve</param>
        static DBNode<DBMovieInfo> GetNodeByName(DBNode<DBMovieInfo> rootNode, string name)
        {
            if (!rootNode.HasChildren) return null;

            return rootNode.Children.FirstOrDefault(n => n.Name == string.Format("${{{0}}}", name));
        }
        /// <summary>
        /// Removes a movie criteria from a node
        /// </summary>
        /// <param name="movie">The movie to remove from the nodes criteria filter</param>
        /// <param name="rootNode">The node that the criteria filter belongs to</param>
        static void RemoveMovieCriteriaFromNode(DBNode<DBMovieInfo> node, string movieId)
        {
            if (!BasicHandler.IsValidImdb(movieId))
                return;

            if (!node.HasFilter || string.IsNullOrEmpty(movieId)) return;

            // find critera match in the nodes filter and then remove
            var criteria = node.Filter.Criteria.FirstOrDefault(c => c.Value.ToString() == movieId);
            if (criteria != null)
                node.Filter.Criteria.Remove(criteria);

            if (node.Filter.Criteria.Count == 0)
            {
                TraktLogger.Info("Adding dummy blacklist criteria to the child '{0}' node filter.", node.Name);
                AddDummyBlacklistToFilter(node.Filter);
            }

            node.Commit();
        }
        /// <summary>
        /// Creates a node in a menu
        /// </summary>
        /// <param name="menu">Categories or Filters menu</param>
        /// <param name="name">Name of node to create</param>
        static void CreateNodeInMenu(DBMenu<DBMovieInfo> menu, string name)
        {
            var node = new DBNode<DBMovieInfo>();
            node.Name = name;

            var nodeSettings = new DBMovieNodeSettings();
            node.AdditionalSettings = nodeSettings;

            // Add node to the end
            node.SortPosition = menu.RootNodes.Count + 1;

            // Add to root node
            menu.RootNodes.Add(node);

            // Committing node to menu
            menu.Commit();
        }
        // adds the given movie to the facade and creates a GUIListItem if neccesary
        private void addCategoryNodeToFacade(DBNode<DBMovieInfo> newNode)
        {
            if (newNode == null || _categoriesFacade == null)
                return;

            // if needed, create a new GUIListItem
            if (!listItems.ContainsKey(newNode)) {
                GUIListItem currItem = new GUIListItem();

                // Try to parse the category name and execute  translations if needed
                currItem.Label = Translation.ParseString(newNode.Name);
                currItem.TVTag = newNode;
                currItem.OnItemSelected += new MediaPortal.GUI.Library.GUIListItem.ItemSelectedHandler(onCategoryNodeSelected);

                listItems[newNode] = currItem;
            }

            // add the listitem
            _categoriesFacade.Add(listItems[newNode]);
        }
        /// <summary>
        /// Add criteria (IMDb ID's) for a movie list to a nodes filter criteria
        /// We don't need to worry about movies that don't exist as they will simply not be visible
        /// </summary>
        /// <param name="name">Name of child node to add filters to</param>
        /// <param name="movieIMDbList">List of IMDb ID's to add </param>
        static void AddMoviesCriteriaToNode(DBNode<DBMovieInfo> node, IEnumerable<string> movieIMDbList)
        {
            if (node == null) return;

            // remove any movies that don't contain IMDb ID's.
            var imdbCriteraToAdd = movieIMDbList.Where(s => !string.IsNullOrEmpty(s)).ToList();

            // clear existing filter
            if (node.HasFilter)
            {
                // do a quick check to see if we need to do anything
                // if the criteria counts matches, determine if the critera values also matches
                if (node.Filter.Criteria.Count == imdbCriteraToAdd.Count)
                {
                    bool requiresUpdate = false;
                    foreach (var criteria in node.Filter.Criteria)
                    {
                        // no point doing any further checks
                        if (requiresUpdate)
                            continue;

                        // check if the current critera list already has the criteria in the filter
                        requiresUpdate = !imdbCriteraToAdd.Contains(criteria.Value.ToString());
                    }

                    // nothing to do with node, it's already up to date
                    if (!requiresUpdate)
                        return;
                }

                node.Filter.WhiteList.Clear();
                node.Filter.BlackList.Clear();
                node.Filter.Delete();
            }

            // create a new filter, such that any criteria will match
            node.Filter = new DBFilter<DBMovieInfo>();
            node.Filter.CriteriaGrouping = DBFilter<DBMovieInfo>.CriteriaGroupingEnum.ONE;
            node.Filter.Name = string.Format("{0} Filter", node.Name);

            // add criteria for each movie
            foreach (var movieId in imdbCriteraToAdd)
            {
                //TraktLogger.Debug("Adding criteria to the '{0}' node filter, Field = 'imdb_id', Value = '{1}'", node.Name, movieId);

                var criteria = new DBCriteria<DBMovieInfo>();
                criteria.Field = DBField.GetFieldByDBName(typeof(DBMovieInfo), "imdb_id");
                criteria.Operator = DBCriteria<DBMovieInfo>.OperatorEnum.EQUAL;
                criteria.Value = movieId;

                // add the criteria to the filter
                node.Filter.Criteria.Add(criteria);
            }

            if (node.Filter.Criteria.Count == 0)
            {
                TraktLogger.Info("Adding dummy blacklist criteria to the '{0}' node filter.", node.Name);
                AddDummyBlacklistToFilter(node.Filter);
            }

            node.Commit();
        }
    private static void GoalPathI(ArrayList goalpath,
		DBNode node, DBNode goal, Stack path)
    {
        //Console.WriteLine ("GoalPathI");
        if (node == null)
            return;

        if (node == goal) {
            foreach (DBNode pNode in path)
                goalpath.Add (pNode);

            goalpath.Reverse ();
            goalpath.Add (node);

            return;
        }

        foreach (DBNode child in node.Children) {
            path.Push (node);
            GoalPathI (goalpath, child, goal, path);
            path.Pop ();
        }
    }
        public static void VerifyCategoryMenu()
        {
            DBMenu<DBTrackInfo> menu = mvCentralCore.Settings.CategoriesMenu;

            if (menu.RootNodes.Count == 0) {
                int position = 1;

                DBNode<DBTrackInfo> allNode = new DBNode<DBTrackInfo>();
                allNode.Name = "${AllmvCentral}";
                allNode.DynamicNode = false;
                allNode.Filter = new DBFilter<DBTrackInfo>();
                allNode.SortPosition = position++;
                allNode.DBManager = mvCentralCore.DatabaseManager;
                menu.RootNodes.Add(allNode);

                DBNode<DBTrackInfo> unwatchedNode = new DBNode<DBTrackInfo>();
                unwatchedNode.Name = "${UnwatchedMusicVideo}";
                unwatchedNode.DynamicNode = false;
                unwatchedNode.Filter = new DBFilter<DBTrackInfo>();
                DBCriteria<DBTrackInfo> criteria = new DBCriteria<DBTrackInfo>();
                criteria.Field = DBField.GetFieldByDBName(typeof(DBUserMusicVideoSettings), "watched");
                criteria.Relation = DBRelation.GetRelation(typeof(DBTrackInfo), typeof(DBUserMusicVideoSettings), "");
                criteria.Operator = DBCriteria<DBTrackInfo>.OperatorEnum.EQUAL;
                criteria.Value = "0";
                unwatchedNode.Filter.Criteria.Add(criteria);
                unwatchedNode.SortPosition = position++;
                unwatchedNode.DBManager = mvCentralCore.DatabaseManager;
                menu.RootNodes.Add(unwatchedNode);

                DBNode<DBTrackInfo> recentNode = new DBNode<DBTrackInfo>();
                recentNode.Name = "${RecentlyAddedmvCentral}";
                recentNode.DynamicNode = false;
                recentNode.Filter = new DBFilter<DBTrackInfo>();
                recentNode.SortPosition = position++;
                recentNode.DBManager = mvCentralCore.DatabaseManager;

                DBCriteria<DBTrackInfo> recentCriteria = new DBCriteria<DBTrackInfo>();
                recentCriteria.Field = DBField.GetFieldByDBName(typeof(DBTrackInfo), "date_added");
                recentCriteria.Operator = DBCriteria<DBTrackInfo>.OperatorEnum.GREATER_THAN;
                recentCriteria.Value = "-30d";
                recentNode.Filter.Criteria.Add(recentCriteria);

                DBMusicVideoNodeSettings additionalSettings = new DBMusicVideoNodeSettings();
                additionalSettings.UseDefaultSorting = false;
            //                additionalSettings.SortField = SortingFields.DateAdded;
            //                additionalSettings.SortDirection = SortingDirections.Descending;
                recentNode.AdditionalSettings = additionalSettings;

                menu.RootNodes.Add(recentNode);

                DBNode<DBTrackInfo> genreNode = new DBNode<DBTrackInfo>();
                genreNode.DynamicNode = true;
                genreNode.BasicFilteringField = DBField.GetFieldByDBName(typeof(DBTrackInfo), "genres");
                genreNode.Name = "${Genres}";
                genreNode.SortPosition = position++;
                genreNode.DBManager = mvCentralCore.DatabaseManager;
                menu.RootNodes.Add(genreNode);

                menu.Commit();
            }

            foreach (DBNode<DBTrackInfo> currNode in menu.RootNodes) {
                currNode.UpdateDynamicNode();
                currNode.Commit();
            }
        }
 /// <summary>
 /// Returns a value indicating wether this node has available movies
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public bool HasAvailableMovies(DBNode<DBMovieInfo> node)
 {
     lock (syncRefresh) {
         HashSet<DBMovieInfo> results = GetAvailableMovies(node);
         return (results.Count > 0);
     }
 }
    private void CheckC2(ArrayList[] affecting)
    {
        int[] n = new int[2];

        for (n[0] = 0 ; n[0] < affecting.Length ; ++n[0]) {
            for (n[1] = (n[0] + 1) ; n[1] < affecting.Length ; ++n[1]) {
                int[] count = new int[2];
                int countN;
                if (affecting[n[0]].Count == 0 || affecting[n[1]].Count == 0)
                    continue;

                do {
                    // Enumerate all possible combinations at position (n0, n1)
                    DBNode node1 = (DBNode) affecting[n[0]][count[0]];
                    DBNode node2 = (DBNode) affecting[n[1]][count[1]];
                    GBSpaceState state1 = (GBSpaceState) node1.State;
                    GBSpaceState state2 = (GBSpaceState) node2.State;

                    // Check that there is a appropiate dependency node in it and
                    // then for combinability for state1/state2
                    if ((thisStageDependencies.Contains (state1) == true ||
                        thisStageDependencies.Contains (state2) == true) &&
                        state2.GB.CompatibleWith (state1.GB) &&
                        gbS.NotInConflict (state1, state2))
                    {
                        GBSpaceState gComb =
                            (GBSpaceState) state2.LastOperator.Apply (gbS, state1);
                        gComb.GB.AddExtraStones (state2.GB);
                        gComb.UpdateLegalOperators (gbS.maximumCategory);

                        // Now check if the new state results in new operators
                        GBOperator[] n1o = state1.LegalOperators;
                        GBOperator[] n2o = state2.LegalOperators;

                        GBOperator[] nCo = gComb.LegalOperators;
                        if (nCo == null)
                            goto nextComb;
                        //Console.WriteLine ("nCo.Length = {0}", nCo.Length);

                        // Check: nCo \setminus (n1o \cup n2o) \neq \emptyset
                        bool seenUnique = false;
                        foreach (GBOperator gbo in nCo) {
                            if (n1o != null && Array.IndexOf (n1o, gbo) >= 0)
                                continue;
                            if (n2o != null && Array.IndexOf (n2o, gbo) >= 0)
                                continue;

                            seenUnique = true;
                            //Console.WriteLine ("unique: {0}", gbo);
                        }
                        if (seenUnique == false)
                            goto nextComb;

                        // We have found a new combination
                        /*
                        Console.WriteLine ("TODO: found found found:");
                        Console.WriteLine ("From 1: {0}", state1.GB);
                        Console.WriteLine ("From 2: {0}", state2.GB);
                        Console.WriteLine ("To: {0}", gComb.GB);
                        throw (new ArgumentException ("DEBUG"));
                        */

                        DBNode combNode = new DBNode (DBNode.NodeType.Combination,
                            gComb, level);
                        combNode.IsGoal = gbS.IsGoal (gComb);

                        /* TODO: have to get this back to db-search somehow,
                         * or throw exception here.
                        if (combNode.IsGoal)
                            goalCount += 1;
                        */

                        dbS.AddCombinationNode (node1, combNode);
                        node2.CombinedChildren.Add (combNode);
                        gbS.RegisterNewNode (combNode);
                    }

        nextComb:
                    for (countN = 0 ; countN < count.Length ; ++countN) {
                        count[countN] += 1;

                        if (count[countN] < affecting[n[countN]].Count)
                            break;

                        count[countN] = 0;
                    }
                } while (countN < count.Length);
            }
        }
    }
        /// <summary>
        /// Removes a child node
        /// </summary>
        /// <param name="rootNode">Parent node to remove node from</param>
        /// <param name="name">The name of the child node to remove</param>
        static void RemoveNode(DBNode<DBMovieInfo> rootNode, string name)
        {
            if (rootNode == null) return;

            string nodeName = name;
            if (!nodeName.StartsWith("$"))
                nodeName = string.Format("${{{0}}}", name);

            try
            {
                // check if the node exists before removing
                var node = rootNode.Children.FirstOrDefault(n => n.Name == nodeName);
                if (node == null) return;

                rootNode.Children.Remove(node);
                rootNode.Children.Commit();

                node.Delete();
            }
            catch (Exception ex)
            {
                TraktLogger.Error("Failed to remove node from MovingPictures, ParentNode='{0}', Name='{1}', Error='{2}'", rootNode, name, ex.Message);
            }
        }
        /// <summary>
        /// Publishes categorie (node) details to the skin instantly
        /// </summary>
        /// <param name="node"></param>
        private void PublishCategoryDetails(DBNode<DBMovieInfo> node)
        {
            if (node == null) {
                // Clear the category related skin properties
                ResetProperties("#MovingPictures.SelectedNode");
            }
            else {
                // Publish category details
                PublishDetails(node, "SelectedNode");
                PublishDetails(node.AdditionalSettings, "SelectedNode.Extra.AdditionalSettings");

                // publish category node name in a format that can always be used as a filename.
                SetProperty("#MovingPictures.SelectedNode.FileFriendlyName", Translation.ParseString(node.Name).ToValidFilename());
            }

            // Publish Category Artwork
            PublishArtwork(node);
        }
 /// <summary>
 /// Returns a list of available movies for this node (includes active filters)
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public HashSet<DBMovieInfo> GetAvailableMovies(DBNode<DBMovieInfo> node)
 {
     lock (syncRefresh) {
         if (FilteredMovies.Count == 0) {
             availableMovies[node] = new HashSet<DBMovieInfo>();
         }
         else if (!availableMovies.ContainsKey(node)) {
             HashSet<DBMovieInfo> nodeResults = new HashSet<DBMovieInfo>(GetPossibleMovies(node));
             // intersect with the filtered movie list meaning that what is
             // not in the filtered movies list will be removed from the base list
             nodeResults.IntersectWith(FilteredMovies);
             availableMovies[node] = nodeResults;
         }
     }
     return availableMovies[node];
 }
        private static void UpdateNodes(DBNode<DBMovieInfo>[] nodes, IEnumerable<TraktMovie> traktRecommendationMovies, IEnumerable<TraktWatchListMovie> traktWatchListMovies)
        {
            if (nodes.Length != 2)
            {
                TraktLogger.Error("We don't have the correct number of nodes to correctly update");
            }

            TraktLogger.Debug("Getting the Movie's from Moving Pictures");
            var movieList = DBMovieInfo.GetAll();

            #region WatchList
            TraktLogger.Debug("Creating the watchlist filter");
            var watchlistFilter = new DBFilter<DBMovieInfo>();
            TraktLogger.Debug("WatchList: {0}", string.Join(", ", traktWatchListMovies.Select(m => m.Title).ToArray()));
            foreach (var movie in traktWatchListMovies.Select(traktmovie => movieList.Find(m => m.ImdbID.CompareTo(traktmovie.Imdb) == 0)).Where(movie => movie != null))
            {
                TraktLogger.Debug("Adding {0} to watchlist", movie.Title);
                watchlistFilter.WhiteList.Add(movie);
            }

            if (watchlistFilter.WhiteList.Count == 0)
            {
                TraktLogger.Debug("Nothing in watchlist, Blacklisting everything");
                watchlistFilter.BlackList.AddRange(movieList);
            }

            TraktLogger.Debug("Retrieving the watchlist node");
            var watchlistNode = nodes[0];
            if (watchlistNode.Filter != null) watchlistNode.Filter.Delete();
            watchlistNode.Filter = watchlistFilter;
            watchlistNode.Commit();
            #endregion

            #region Recommendations
            TraktLogger.Debug("Creating the recommendations filter");
            var recommendationsFilter = new DBFilter<DBMovieInfo>();
            foreach (var movie in traktRecommendationMovies.Select(traktMovie => movieList.Find(m => m.ImdbID.CompareTo(traktMovie.Imdb) == 0)).Where(movie => movie != null))
            {
                TraktLogger.Debug("Adding {0} to recommendations", movie.Title);
                recommendationsFilter.WhiteList.Add(movie);
            }

            if (recommendationsFilter.WhiteList.Count == 0)
            {
                TraktLogger.Debug("Nothing in recommendation list, Blacklisting everything");
                recommendationsFilter.BlackList.AddRange(movieList);
            }

            TraktLogger.Debug("Retrieving the recommendations node");
            var recommendationsNode = nodes[1];
            if (recommendationsNode.Filter != null) recommendationsNode.Filter.Delete();
            recommendationsNode.Filter = recommendationsFilter;
            recommendationsNode.Commit();
            #endregion
        }
 private void removeFilters(DBNode<DBMovieInfo> node)
 {
     foreach (IFilter<DBMovieInfo> currFilter in node.GetAllFilters())
         if (Filters.Contains(currFilter))
             Filters.Remove(currFilter);
 }
        private static IEnumerable<DBNode<DBMovieInfo>> CreateNodes(bool watchlist, bool recommendations)
        {
            List<DBNode<DBMovieInfo>> nodesAdded = new List<DBNode<DBMovieInfo>>();

            if (watchlist)
            {
                var watchlistNode = new DBNode<DBMovieInfo> { Name = "${" + GUI.Translation.WatchList + "}" };

                var watchlistSettings = new DBMovieNodeSettings();
                watchlistNode.AdditionalSettings = watchlistSettings;

                nodesAdded.Add(watchlistNode);
            }

            if (recommendations)
            {
                var recommendationsNode = new DBNode<DBMovieInfo> { Name = "${" + GUI.Translation.Recommendations + "}" };

                var recommendationsSettings = new DBMovieNodeSettings();
                recommendationsNode.AdditionalSettings = recommendationsSettings;

                nodesAdded.Add(recommendationsNode);
            }

            return nodesAdded;
        }
        public static void VerifyFilterMenu()
        {
            DBMenu<DBTrackInfo> menu = mvCentralCore.Settings.FilterMenu;

            if (menu.RootNodes.Count == 0) {
                int position = 1;

                DBNode<DBTrackInfo> unwatchedNode = new DBNode<DBTrackInfo>();
                unwatchedNode.Name = "${UnwatchedmvCentral}";
                unwatchedNode.DynamicNode = false;
                unwatchedNode.Filter = new DBFilter<DBTrackInfo>();
                DBCriteria<DBTrackInfo> criteria = new DBCriteria<DBTrackInfo>();
                criteria.Field = DBField.GetFieldByDBName(typeof(DBUserMusicVideoSettings), "watched");
                criteria.Relation = DBRelation.GetRelation(typeof(DBTrackInfo), typeof(DBUserMusicVideoSettings), "");
                criteria.Operator = DBCriteria<DBTrackInfo>.OperatorEnum.EQUAL;
                criteria.Value = "0";
                unwatchedNode.Filter.Criteria.Add(criteria);
                unwatchedNode.SortPosition = position++;
                unwatchedNode.DBManager = mvCentralCore.DatabaseManager;
                menu.RootNodes.Add(unwatchedNode);

                DBNode<DBTrackInfo> genreNode = new DBNode<DBTrackInfo>();
                genreNode.DynamicNode = true;
                genreNode.BasicFilteringField = DBField.GetFieldByDBName(typeof(DBTrackInfo), "genres");
                genreNode.Name = "${Genre}";
                genreNode.DBManager = mvCentralCore.DatabaseManager;
                genreNode.SortPosition = position++;
                menu.RootNodes.Add(genreNode);

                DBNode<DBTrackInfo> dateNode = new DBNode<DBTrackInfo>();
                dateNode.DynamicNode = true;
                dateNode.BasicFilteringField = DBField.GetFieldByDBName(typeof(DBTrackInfo), "date_added");
                dateNode.Name = "${DateAdded}";
                dateNode.DBManager = mvCentralCore.DatabaseManager;
                dateNode.SortPosition = position++;
                menu.RootNodes.Add(dateNode);

                menu.Commit();
            }

            foreach (DBNode<DBTrackInfo> currNode in menu.RootNodes)
            {
                currNode.UpdateDynamicNode();
                currNode.Commit();
            }
        }
 private static void RemoveMovieFromNode(DBMovieInfo movie, DBNode<DBMovieInfo> rootNode)
 {
     foreach (var node in rootNode.Children)
     {
         node.Filter.WhiteList.Remove(movie);
         if (node.Filter.WhiteList.Count == 0)
         {
             var filter = new DBFilter<DBMovieInfo>();
             filter.BlackList.AddRange(DBMovieInfo.GetAll());
             node.Filter.Delete();
             node.Filter = filter;
         }
         node.Commit();
     }
 }
    /** Test a potential winning threat sequence for refutability.
     *
     * @param curBoard The original board the original attacker db-search was
     * started with (root.State.GB).
     * @param root The root node of the search tree.
     * @param goalnode The new goal node identified by db-search.
     *
     * @returns null if the sequence is refutable, otherwise the sequence
     * itself is returned.
     */
    public static GBThreatSequence DefenseRefutable(GoBangBoard curBoard,
		DBNode root, DBNode goalnode)
    {
        // First create the goal path, that is, all nodes that lie on the
        // direct child path to the node.
        ArrayList gp = GBThreatSequence.GoalPath (root, goalnode);

        // Check if there is a clear refutable path node in the path and
        // return early if this is the case.
        //Console.WriteLine ("Path:");
        foreach (DBNode gpN in gp) {
            //Console.WriteLine ("   {0}", gpN);
            if (gpN.IsRefutePathRoot) {
                //Console.WriteLine ("DEBUG: node in refutepath");
                return (null);
            }
        }

        // Now combine the operators and build a one-by-one threat sequence.
        GBThreatSequence seq = GBThreatSequence.BuildThreatSequence (gp);

        // Clone and flip board
        GoBangBoard gbFlipped = (GoBangBoard) curBoard.Clone ();
        gbFlipped.Flip ();

        Console.Write ("  checking potential {0} pair-move sequence: ", gp.Count);
        Console.Out.Flush ();

        int refutes = DefenseRefutes (seq, gbFlipped);
        if (refutes < 0) {
            Console.WriteLine ("un-refutable");
            return (seq);
        }

        Console.WriteLine ("refutable at pair-move {0}", refutes);

        // Mark root of refutation
        if (refutes < (gp.Count-1)) {
            DBNode refutePathRoot = (DBNode) gp[refutes+1];
            refutePathRoot.IsRefutePathRoot = true;
        }

        return (null);
    }
    public static GBThreatSequence[] BuildAllGoalPathes(GBSearchModule module,
		DBNode root)
    {
        ArrayList goalpathes = GoalPathes (module, root);
        Console.WriteLine ("I have {0} goal pathes", goalpathes.Count);

        // Create the threat sequences.
        ArrayList threatSeqs = new ArrayList ();

        // Build one individual threat sequence for each goalpath.
        foreach (ArrayList gp in goalpathes) {
            GBThreatSequence ts = BuildThreatSequence (gp);
            threatSeqs.Add (ts);
        }

        // DEBUG output
        Console.WriteLine ("{0} threat seqs lists", threatSeqs.Count);
        int seqNo = 1;
        foreach (GBThreatSequence seqW in threatSeqs) {
            GBThreatSequence seq = seqW;
            Console.WriteLine ();

            Console.WriteLine (((GBSpaceState) root.State).GB);
            Console.WriteLine ();
            Console.WriteLine ("Sequence {0}: ", seqNo);

            int m = 0;
            while (seq != null) {
                Console.WriteLine ("  move{0}: {1}, threat class {2}", m,
                    seq.attacker, seq.attackerThreatClass);
                m += 1;

                foreach (GBMove reply in seq.defender) {
                    Console.WriteLine ("      def-reply{0}: {1}", m, reply);
                    m += 1;
                }

                seq = seq.next;
            }

            seqNo += 1;
        }

        return ((GBThreatSequence[])
            threatSeqs.ToArray (typeof (GBThreatSequence)));
    }
        /// <summary>
        /// Created a child node
        /// </summary>
        /// <param name="rootNode">The parent node to create a node under</param>
        /// <param name="name">Name of new child node</param>
        /// <returns>Returns the existing child node if it exists otherwise creates a new one</returns>
        static DBNode<DBMovieInfo> CreateNode(DBNode<DBMovieInfo> rootNode, string name, bool createBlacklist = false)
        {
            if (rootNode == null) return null;

            string nodeName = name;
            if (!nodeName.StartsWith("$"))
                nodeName = string.Format("${{{0}}}", name);

            // check if the node exists, if not create it
            var node = rootNode.Children.FirstOrDefault(n => n.Name == nodeName);

            // we have it, nothing else to do
            if (node != null)
                return node;

            TraktLogger.Info("Creating child node '{0}' under Trakt", name);

            // create the node with default settings
            node = new DBNode<DBMovieInfo> { Name = nodeName };

            var nodeSettings = new DBMovieNodeSettings();
            node.AdditionalSettings = nodeSettings;

            if (createBlacklist)
            {
                TraktLogger.Info("Adding dummy blacklist criteria to the '{0}' node filter", name);
                node.Filter = new DBFilter<DBMovieInfo>();
                node.Filter.CriteriaGrouping = DBFilter<DBMovieInfo>.CriteriaGroupingEnum.ONE;
                node.Filter.Name = string.Format("{0} Filter", nodeName);
                AddDummyBlacklistToFilter(node.Filter);
            }

            // add as a child to the root node
            node.Parent = rootNode;
            rootNode.Children.Add(node);
            rootNode.Commit();

            return node;
        }
 // TODO: Refactor to DBNode.
 private BrowserViewMode GetViewFromNode(DBNode<DBMovieInfo> node)
 {
     DBMovieNodeSettings nodeSettings = (DBMovieNodeSettings)node.AdditionalSettings;
     if (nodeSettings.MovieView == BrowserViewMode.PARENT) {
         if (node.Parent != null)
             return GetViewFromNode(node.Parent);
         else
             return MovingPicturesCore.Settings.DefaultView;
     }
     else
         return nodeSettings.MovieView;
 }