Пример #1
0
        static PatriciaTrie LoadTranslationTree(String currentKey)
        {
            //check if tree is already stored in memory
            if (NinjaTranslateMain.treesInMemory.ContainsKey(currentKey))
            {
                return(NinjaTranslateMain.treesInMemory[currentKey]);
            }

            //load windows
            SplashForm sf = new SplashForm();

            //TODO Change following with filter structure to be more flexible
            Normalizer normalizer = new Normalizer();

            //load data
            DictLoader dc = new DictLoader();

            dc.SetSplashForm(sf);
            dc.SetFilter(normalizer); //TODO this has to be replaced when filters are implemented

            if (!NinjaTranslateMain.rawFiles.ContainsKey(currentKey))
            {
                MessageBox.Show("Quick change key contains an unknown dictionary name. No dictionary was loaded!");
                return(null);
            }

            PatriciaTrie translationTree = dc.LoadDictData(NinjaTranslateMain.rawFiles[currentKey], Config.GetValue("serializedPath") + currentKey + ".tree");

            if (translationTree == null)
            {
                MessageBox.Show("Could not find a dictionary with the specified name. No tree was loaded.");
                return(null);
            }

            //if we are allowed to store this tree in memory, even when we load another one -> store it
            if (NinjaTranslateMain.treesInMemory.Count < NinjaTranslateMain.maxTreesInMemory)
            {
                NinjaTranslateMain.treesInMemory.Add(currentKey, translationTree);
            }

            return(translationTree);
        }
Пример #2
0
        /// <summary>
        /// Creates a PatrixiaTrie that will be used for translation etc.
        /// </summary>
        /// <param name="fileToLoad">Path to a tvs source file to be parsed.</param>
        /// <param name="serializedFile">Path to a serialized version of the fileToLoad, will be prefered when found</param>
        /// <returns></returns>
        public PatriciaTrie LoadDictData(String fileToLoad, String serializedFile)
        {
            PatriciaTrie pTrie = new PatriciaTrie();

            serializedFile = Path.Combine(this.pathPrefix, serializedFile);

            //serialized file found, use this one
            if (File.Exists(serializedFile))
            {
                //reset status informations of FileMapper for next run
                PatrixiaTrie.PatrixiaTrieFileMapper.ResetDeserializationProgress();

                //load via backgroundWorker, report progress to splashform
                BackgroundWorker bw = new BackgroundWorker();
                bw.WorkerReportsProgress = true;
                //the following handler will be executed asynchronous
                bw.DoWork += new DoWorkEventHandler(
                    delegate(object sender, DoWorkEventArgs args) {
                    byte[] data = File.ReadAllBytes(serializedFile);
                    pTrie.setRootNode(PatrixiaTrie.PatrixiaTrieFileMapper.Deserialize(data));
                });
                bw.RunWorkerAsync();

                //show SplashForm
                if (sF != null)
                {
                    sF.Show();
                }
                //update progressbar while loading
                while (PatrixiaTrie.PatrixiaTrieFileMapper.deserializationProgress < 100)
                {
                    sF.getProgressBar().Value = PatrixiaTrie.PatrixiaTrieFileMapper.deserializationProgress;
                    Thread.Sleep(100);
                }

                //hide SplashForm
                if (sF != null)
                {
                    sF.Close();
                }
            }
            //no serialized file found, try reading the raw file
            else if (File.Exists(fileToLoad))
            {
                using (StreamReader sr = new StreamReader(fileToLoad)) {
                    string   line      = sr.ReadLine();
                    int      counter   = 1;
                    int      lineCount = File.ReadLines(@fileToLoad).Count();
                    string[] wordArray;
                    pTrie.init("");

                    if (sF != null)
                    {
                        sF.Show();
                    }

                    while (line != null)
                    {
                        wordArray = line.Split('\t');
                        if (wordArray.Count() > 1)
                        {
                            String word        = wordArray[0];
                            String translation = wordArray[1];

                            //TODO pretty magic, this number, maybe sth with lineCount in it?
                            if (counter % (10000) == 0)
                            {
                                sF.getProgressBar().Value = (int)((counter * 100) / lineCount); //sets value of progressbar
                            }
                            //apply filter
                            String filteredWord = this.ApplyFilters(word);
                            if (filteredWord != null)
                            {
                                pTrie.insertQuery(filteredWord, translation);
                            }
                            counter++;
                        }
                        line = sr.ReadLine();
                    }

                    if (sF != null)
                    {
                        sF.Close();
                    }

                    //serialize tree for next start
                    byte[] serialization = PatrixiaTrie.PatrixiaTrieFileMapper.Serialize(pTrie.getRootNode());
                    SaveData(serializedFile, serialization);
                }
            }
            // when no path for a dictionary file is stated.
            else
            {
                Console.Write("No path for dictionary file - DictLoader");
            }

            return(pTrie);
        }
Пример #3
0
        static void Main()
        {
            //Initiate update process
            //deactivated for now, though it does work!
            //NinjaTranslateMain.Update(Config.GetValue("version"), Config.GetValue("updateStep"));

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

            //load windows
            MainWindow       mainWindow       = new MainWindow();
            NotificationForm notificationForm = new NotificationForm();

            //load config values
            LoadConfigFiles(mainWindow);

            //load tree
            PatriciaTrie translationTree = LoadTranslationTree(currentFileKey);

            //TODO normalizer is used for input and  parsing -> surely no problem when we finally add filters
            Normalizer normalizer = new Normalizer();

            //initiate translation center
            translationCenter = new TranslationCenter();
            translationCenter.SetFilter(normalizer);
            translationCenter.SetTranslationTree(translationTree);

            //initiate notification service
            CustomNotification notification = new CustomNotification();

            notification.setHeight(Int32.Parse(Config.GetValue("windowHeight")));
            notification.setWidth(Int32.Parse(Config.GetValue("windowWidth")));
            notification.SetForm(notificationForm);

            //initiate sources to be translated from
            SystemSource systemSource         = new SystemSource();
            int          clipboardAccessTimer = 500;

            int.TryParse(Config.GetValue("clipboardAccessTimer"), out clipboardAccessTimer);
            systemSource.SetClipboardAccessTimer(clipboardAccessTimer);
            systemSource.SetTranslationService(translationCenter);
            systemSource.SetNotificationService(notification);

            InputForm inputSource = new InputForm();

            inputSource.SetTranslationService(translationCenter);
            inputSource.SetNotificationService(notification);

            //register hooks
            KeyboardHook markerHook     = new KeyboardHook();
            KeyboardHook inputHook      = new KeyboardHook();
            KeyboardHook dictionaryHook = new KeyboardHook();

            try {
                // register the control + alt + N combination as hot key to translate current selection.
                markerHook.KeyPressed += new EventHandler <KeyPressedEventArgs>(delegate(object sender, KeyPressedEventArgs e) {
                    systemSource.TriggerTranslation(true);
                });
                markerHook.RegisterHotKey((ModifierKeys)2 | (ModifierKeys)1, Keys.N);
                // register the control + alt + B combination as hot key to open up input formular.
                inputHook.KeyPressed += new EventHandler <KeyPressedEventArgs>(delegate(object sender, KeyPressedEventArgs e) {
                    inputSource.TriggerTranslation(true);
                });
                inputHook.RegisterHotKey((ModifierKeys)2 | (ModifierKeys)1, Keys.B);
                //register the control + alt + V combination to trigger a switch of the chosen dictionary
                dictionaryHook.KeyPressed += new EventHandler <KeyPressedEventArgs>(delegate(object sender, KeyPressedEventArgs e) {
                    //reload in case user has added a dict
                    NinjaTranslateMain.rawFiles       = Config.GetMultiValue("path");
                    NinjaTranslateMain.quickChangeKey = Config.GetValue("quickchangeKey");
                    NinjaTranslateMain.currentFileKey = Config.GetValue("currentKey");
                    NinjaTranslateMain.ChangeDictionary(notification);
                });
                dictionaryHook.RegisterHotKey((ModifierKeys)2 | (ModifierKeys)1, Keys.V);
            }
            catch (InvalidOperationException e) {
                System.Windows.Forms.MessageBox.Show("NinjaTranslate couldn't register the necessary hotkeys. It seems like another program uses them. Try to close them :)", "NinjaTranslate found an error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //check if construction went well or if window is marked as indisposed
            if (!mainWindow.IsDisposed)
            {
                Application.Run(mainWindow);
            }

            GC.KeepAlive(markerHook);
            GC.KeepAlive(dictionaryHook);
            GC.KeepAlive(inputHook);
        }
Пример #4
0
 public void SetTranslationTree(PatriciaTrie transTree)
 {
     this.translationTree = transTree;
 }