Example #1
0
WordsEdit::WordsEdit( QWidget *parent, const char *name, int win_num, ResourcesWin *res )
    : QWidget( parent, name ,Qt::WDestructiveClose )
{
  
  setCaption("WORDS.TOK Editor");
  wordlist = new WordList();

  winnum = win_num;
  resources_win = res;
  wordsfind = NULL;
  
  Q3PopupMenu *file = new Q3PopupMenu( this );
  Q_CHECK_PTR( file );

  file->insertItem( "New", this, SLOT(new_file()) );
  file->insertItem( "Open", this, SLOT(open_file()) );
  file->insertItem( "Merge", this, SLOT(merge_file()) );
  file->insertItem( "Save", this, SLOT(save_file()) );
  file->insertItem( "Save As", this, SLOT(save_as_file()) );
  file->insertSeparator();
  file->insertItem( "Close", this, SLOT(close()) );

  Q3PopupMenu *words = new Q3PopupMenu( this );
  Q_CHECK_PTR( words );

  words->insertItem( "Add word group", this, SLOT(add_group_cb()) );
  words->insertItem( "Delete word group", this, SLOT(delete_group_cb()) );
  words->insertItem( "Change group number", this, SLOT(change_group_number_cb()) );
  words->insertSeparator();
  words->insertItem( "Add word", this, SLOT(add_word_cb()) );
  words->insertItem( "Delete word", this, SLOT(delete_word_cb()) );
  words->insertSeparator();
  words->insertItem( "Count word groups", this, SLOT(count_groups_cb()) );
  words->insertItem( "Count words", this, SLOT(count_words_cb()) );
  words->insertItem( "&Find...", this, SLOT(find_cb()) , Qt::CTRL+Qt::Key_F);


  QMenuBar *menu = new QMenuBar(this);  
  Q_CHECK_PTR( menu );
  menu->insertItem( "File", file );
  menu->insertItem( "Words", words );
  menu->setSeparator( QMenuBar::InWindowsStyle );

  Q3BoxLayout *all =  new Q3VBoxLayout(this,10);

  QSplitter *split = new QSplitter(Qt::Horizontal,this);


  QWidget *left = new QWidget(split);
  Q3BoxLayout *lgroup = new Q3VBoxLayout(left,4);   
  QLabel *labelgroup = new QLabel("Word groups",left,"Word groups");
  labelgroup->setAlignment(Qt::AlignCenter);  
  lgroup->addWidget(labelgroup);
  
  listgroup = new Q3ListBox(left);
  listgroup->setColumnMode (1);
  listgroup->setMinimumSize(200,300);
  connect( listgroup, SIGNAL(highlighted(int)), SLOT(select_group(int)) );
  connect( listgroup, SIGNAL(selected(int)), SLOT(select_group(int)) );

  lgroup->addWidget(listgroup);


  QWidget *right = new QWidget(split);
  Q3BoxLayout *lwords =  new Q3VBoxLayout(right,4);
  labelword = new QLabel("Word group",right,"Word group");
  labelword->setAlignment(Qt::AlignCenter);
  lwords->addWidget(labelword);

  listwords = new Q3ListBox(right);
  listwords->setColumnMode (1);
  listwords->setMinimumSize(200,300);
  connect( listwords, SIGNAL(highlighted(int)), SLOT(select_word(int)) );
  connect( listwords, SIGNAL(selected(int)), SLOT(select_word(int)) );
  lwords->addWidget(listwords);
  
  lineword = new QLineEdit(right);
  lineword->setEnabled(false);
  connect( lineword, SIGNAL(returnPressed()), SLOT(do_add_word()) );
  lwords->addWidget(lineword);  
  

  all->addWidget(split);  

  Q3BoxLayout *buttons =  new Q3HBoxLayout(all,20);

  add_group = new QPushButton("Add group",this);
  connect( add_group, SIGNAL(clicked()), SLOT(add_group_cb()) );
  buttons->addWidget(add_group);

  delete_group = new QPushButton("Delete group",this);
  connect( delete_group, SIGNAL(clicked()), SLOT(delete_group_cb()) );
  buttons->addWidget(delete_group);

  add_word = new QPushButton("Add word",this);
  connect( add_word, SIGNAL(clicked()), SLOT(add_word_cb()) );
  buttons->addWidget(add_word);

  delete_word = new QPushButton("Delete word",this);
  connect( delete_word, SIGNAL(clicked()), SLOT(delete_word_cb()) );
  buttons->addWidget(delete_word);

  Q3BoxLayout *buttons1 =  new Q3HBoxLayout(all,20);

  change_group_number = new QPushButton("&Change group number",this);
  connect( change_group_number, SIGNAL(clicked()), SLOT(change_group_number_cb()) );
  buttons1->addWidget(change_group_number);

  find = new QPushButton("Find",this);
  connect( find, SIGNAL(clicked()), SLOT(find_cb()) );
  buttons1->addWidget(find);
  

  adjustSize();

  changed=false;
  filename="";
  SelectedGroup=0;
  FindLastGroup = FindLastWord = -1;
}
/**
 * @brief Server::CMDcopy
 * @param resp
 * @return
 * метод копирует директорию/файл
 */
std::string Server::CMDcopy(ResponceItem* resp)
{
    std::string result("");
    FSNode* find_src = 0; //
    FSNode* find_dest = 0; //

    resp->response.result = CMD_RESULT_OK;

    resp->client->Lock();

    //обработка источника
    size_t pos = resp->response.address.find('/',0); //относительный или полный путь
    if(pos == std::string::npos || pos > 0)
    {
        //относительно текущей
        find_src = resp->client->GetCurrentDir()->Find("/" + resp->response.address, resp->client->GetCurrentDir());
    }
    else
    {
        //относительно корня
        find_src = fs->Find(resp->response.address, fs);
    }

    if(find_src == 0)
    {
        if(resp->response.code == CMD_RD)
            resp->response.result = CMD_RESULT_UNKNOWN_DIR;

        if(resp->response.code == CMD_DEL)
            resp->response.result = CMD_RESULT_UNKNOWN_FILE;

        resp->client->Unlock();
        return result;
    }


    pos = resp->response.value.find('/',0); //относительный или полный путь
    if(pos == std::string::npos || pos > 0)
    {
        //относительно текущей
        find_dest = resp->client->GetCurrentDir()->Find("/" + resp->response.value, resp->client->GetCurrentDir());
    }
    else
    {
        //относительно корня
        find_dest = fs->Find(resp->response.value, fs);
    }

    if(find_dest == 0)
    {
        if(resp->response.code == CMD_RD)
            resp->response.result = CMD_RESULT_UNKNOWN_DIR;

        if(resp->response.code == CMD_DEL)
            resp->response.result = CMD_RESULT_UNKNOWN_FILE;

        resp->client->Unlock();
        return result;
    }


    if(find_dest->GetType() == FSNode::TYPE_FILE)
    {
        resp->response.result = CMD_RESULT_BAD_REQUES;
        resp->client->Unlock();
        return result;
    }

    //проверка наличия копии
    FSNode* find_copy = find_dest->Find("/" + find_src->GetName(), find_dest);

    if(find_copy != 0) //что-то нашли
    {
        if(find_copy->GetType() == find_src->GetType())
        {
            if(find_src->GetType() == FSNode::TYPE_DIR)
                resp->response.result = CMD_RESULT_DIR_ALREADY_EXISTS;

            if(find_src->GetType() == FSNode::TYPE_FILE)
                resp->response.result = CMD_RESULT_FILE_ALREADY_EXISTS;

            resp->client->Unlock();
            return result;
        }
    }

    if(find_src->GetType() == FSNode::TYPE_DIR)
    {
        FSDir new_dir(find_src->GetName());
        *((FSDir*)find_dest) += new_dir;
        find_dest = find_dest->GetNodeContent()->back();
    }

    if(find_src->GetType() == FSNode::TYPE_FILE)
    {
        FSFile new_file(find_src->GetName());
        *((FSDir*)find_dest) += new_file;
        find_dest = find_dest->GetNodeContent()->back();
    }

    FSNode::_copy(find_src, find_dest); //копирование содержания, если оно есть

    result = "BROADCAST: " + resp->response.user + " performs command: COPY " + resp->response.address + " " + resp->response.value;

    resp->client->Unlock();

    return result;
}
Example #3
0
 CreateEntryResult RamFileSystem::create_file(uint32_t folder_id, const std::string &name)
 {
     return add_entry(folder_id, name, new_file(folder_id));
 }
Example #4
0
int main(int argc, char **argv)
{
  Ihandle *dlg, *vbox, *multitext, *menu;
  Ihandle *sub_menu_file, *file_menu, *item_exit, *item_new, *item_open, *item_save, *item_saveas, *item_revert;
  Ihandle *sub_menu_edit, *edit_menu, *item_find, *item_goto, *item_copy, *item_paste, *item_cut, *item_delete, *item_select_all;
  Ihandle *btn_cut, *btn_copy, *btn_paste, *btn_find, *btn_new, *btn_open, *btn_save;
  Ihandle *sub_menu_format, *format_menu, *item_font;
  Ihandle *sub_menu_help, *help_menu, *item_about;
  Ihandle *sub_menu_view, *view_menu, *item_toolbar, *item_statusbar;
  Ihandle *lbl_statusbar, *toolbar_hb, *recent_menu;
  Ihandle *config;
  const char* font;

  IupOpen(&argc, &argv);
  IupImageLibOpen();

  config = IupConfig();
  IupSetAttribute(config, "APP_NAME", "simple_notepad");
  IupConfigLoad(config);

  multitext = IupText(NULL);
    IupSetAttribute(multitext, "MULTILINE", "YES");
    IupSetAttribute(multitext, "EXPAND", "YES");
    IupSetAttribute(multitext, "NAME", "MULTITEXT");
    IupSetAttribute(multitext, "DIRTY", "NO");
    IupSetCallback(multitext, "CARET_CB", (Icallback)multitext_caret_cb);
    IupSetCallback(multitext, "VALUECHANGED_CB", (Icallback)multitext_valuechanged_cb);
    IupSetCallback(multitext, "DROPFILES_CB", (Icallback)dropfiles_cb);

  font = IupConfigGetVariableStr(config, "MainWindow", "Font");
  if (font)
    IupSetStrAttribute(multitext, "FONT", font);

  lbl_statusbar = IupLabel("Lin 1, Col 1");
    IupSetAttribute(lbl_statusbar, "NAME", "STATUSBAR");  
    IupSetAttribute(lbl_statusbar, "EXPAND", "HORIZONTAL");
    IupSetAttribute(lbl_statusbar, "PADDING", "10x5");

  item_new = IupItem("New\tCtrl+N", NULL);
    IupSetAttribute(item_new, "IMAGE", "IUP_FileNew");
    IupSetCallback(item_new, "ACTION", (Icallback)item_new_action_cb);
  btn_new = IupButton(NULL, NULL);
    IupSetAttribute(btn_new, "IMAGE", "IUP_FileNew");
    IupSetAttribute(btn_new, "FLAT", "Yes");
    IupSetCallback(btn_new, "ACTION", (Icallback)item_new_action_cb);
    IupSetAttribute(btn_new, "TIP", "New (Ctrl+N)");
    IupSetAttribute(btn_new, "CANFOCUS", "No");

  item_open = IupItem("&Open...\tCtrl+O", NULL);
    IupSetAttribute(item_open, "IMAGE", "IUP_FileOpen");
    IupSetCallback(item_open, "ACTION", (Icallback)item_open_action_cb);
  btn_open = IupButton(NULL, NULL);
    IupSetAttribute(btn_open, "IMAGE", "IUP_FileOpen");
    IupSetAttribute(btn_open, "FLAT", "Yes");
    IupSetCallback(btn_open, "ACTION", (Icallback)item_open_action_cb);
    IupSetAttribute(btn_open, "TIP", "Open (Ctrl+O)");
    IupSetAttribute(btn_open, "CANFOCUS", "No");

  item_save = IupItem("Save\tCtrl+S", NULL);
    IupSetAttribute(item_save, "NAME", "ITEM_SAVE");
    IupSetAttribute(item_save, "IMAGE", "IUP_FileSave");
    IupSetCallback(item_save, "ACTION", (Icallback)item_save_action_cb);
  btn_save = IupButton(NULL, NULL);
    IupSetAttribute(btn_save, "IMAGE", "IUP_FileSave");
    IupSetAttribute(btn_save, "FLAT", "Yes");
    IupSetCallback(btn_save, "ACTION", (Icallback)item_save_action_cb);
    IupSetAttribute(btn_save, "TIP", "Save (Ctrl+S)");
    IupSetAttribute(btn_save, "CANFOCUS", "No");

  item_saveas = IupItem("Save &As...", NULL);
    IupSetAttribute(item_saveas, "NAME", "ITEM_SAVEAS");
    IupSetCallback(item_saveas, "ACTION", (Icallback)item_saveas_action_cb);

  item_revert = IupItem("Revert", NULL);
    IupSetAttribute(item_revert, "NAME", "ITEM_REVERT");
    IupSetCallback(item_revert, "ACTION", (Icallback)item_revert_action_cb);
    
  item_exit = IupItem("E&xit", NULL);
    IupSetCallback(item_exit, "ACTION", (Icallback)item_exit_action_cb);

  item_find = IupItem("&Find...\tCtrl+F", NULL);
    IupSetAttribute(item_find, "IMAGE", "IUP_EditFind");
    IupSetCallback(item_find, "ACTION", (Icallback)item_find_action_cb);
  btn_find = IupButton(NULL, NULL);
    IupSetAttribute(btn_find, "IMAGE", "IUP_EditFind");
    IupSetAttribute(btn_find, "FLAT", "Yes");
    IupSetCallback(btn_find, "ACTION", (Icallback)item_find_action_cb);
    IupSetAttribute(btn_find, "TIP", "Find (Ctrl+F)");
    IupSetAttribute(btn_find, "CANFOCUS", "No");

  item_cut = IupItem("Cut\tCtrl+X", NULL);
    IupSetAttribute(item_cut, "NAME", "ITEM_CUT");
    IupSetAttribute(item_cut, "IMAGE", "IUP_EditCut");
    IupSetCallback(item_cut, "ACTION", (Icallback)item_cut_action_cb);
  item_copy = IupItem("Copy\tCtrl+C", NULL);
    IupSetAttribute(item_copy, "NAME", "ITEM_COPY");  
    IupSetAttribute(item_copy, "IMAGE", "IUP_EditCopy");
    IupSetCallback(item_copy, "ACTION", (Icallback)item_copy_action_cb);
  item_paste = IupItem("Paste\tCtrl+V", NULL);
    IupSetAttribute(item_paste, "NAME", "ITEM_PASTE");
    IupSetAttribute(item_paste, "IMAGE", "IUP_EditPaste");
    IupSetCallback(item_paste, "ACTION", (Icallback)item_paste_action_cb);
  item_delete = IupItem("Delete\tDel", NULL);
    IupSetAttribute(item_delete, "IMAGE", "IUP_EditErase");  
    IupSetAttribute(item_delete, "NAME", "ITEM_DELETE");
    IupSetCallback(item_delete, "ACTION", (Icallback)item_delete_action_cb);
  item_select_all = IupItem("Select All\tCtrl+A", NULL);
    IupSetCallback(item_select_all, "ACTION", (Icallback)item_select_all_action_cb);

  btn_cut = IupButton(NULL, NULL);
    IupSetAttribute(btn_cut, "IMAGE", "IUP_EditCut");
    IupSetAttribute(btn_cut, "FLAT", "Yes");
    IupSetCallback(btn_cut, "ACTION", (Icallback)item_cut_action_cb);
  btn_copy = IupButton(NULL, NULL);
    IupSetAttribute(btn_copy, "IMAGE", "IUP_EditCopy");
    IupSetAttribute(btn_copy, "FLAT", "Yes");
    IupSetCallback(btn_copy, "ACTION", (Icallback)item_copy_action_cb);
  btn_paste = IupButton(NULL, NULL);
    IupSetAttribute(btn_paste, "IMAGE", "IUP_EditPaste");
    IupSetAttribute(btn_paste, "FLAT", "Yes");
    IupSetCallback(btn_paste, "ACTION", (Icallback)item_paste_action_cb);

  toolbar_hb = IupHbox(
    btn_new,
    btn_open,
    btn_save,
    IupSetAttributes(IupLabel(NULL), "SEPARATOR=VERTICAL"),
    btn_cut,
    btn_copy,
    btn_paste,
    IupSetAttributes(IupLabel(NULL), "SEPARATOR=VERTICAL"),
    btn_find,
    NULL);
  IupSetAttribute(toolbar_hb, "MARGIN", "5x5");
  IupSetAttribute(toolbar_hb, "GAP", "2");

  item_toolbar = IupItem("&Toobar", NULL);
  IupSetCallback(item_toolbar, "ACTION", (Icallback)item_toolbar_action_cb);
  IupSetAttribute(item_toolbar, "VALUE", "ON");
  item_statusbar = IupItem("&Statusbar", NULL);
  IupSetCallback(item_statusbar, "ACTION", (Icallback)item_statusbar_action_cb);
  IupSetAttribute(item_statusbar, "VALUE", "ON");

  if (!IupConfigGetVariableIntDef(config, "MainWindow", "Toolbar", 1))
  {
    IupSetAttribute(item_toolbar, "VALUE", "OFF");

    IupSetAttribute(toolbar_hb, "FLOATING", "YES");
    IupSetAttribute(toolbar_hb, "VISIBLE", "NO");
  }

  if (!IupConfigGetVariableIntDef(config, "MainWindow", "Statusbar", 1))
  {
    IupSetAttribute(item_statusbar, "VALUE", "OFF");

    IupSetAttribute(lbl_statusbar, "FLOATING", "YES");
    IupSetAttribute(lbl_statusbar, "VISIBLE", "NO");
  }

  item_goto = IupItem("&Go To...\tCtrl+G", NULL);
    IupSetCallback(item_goto, "ACTION", (Icallback)item_goto_action_cb);

  item_font = IupItem("&Font...", NULL);
    IupSetCallback(item_font, "ACTION", (Icallback)item_font_action_cb);
  item_about = IupItem("&About...", NULL);
    IupSetCallback(item_about, "ACTION", (Icallback)item_about_action_cb);

  recent_menu = IupMenu(NULL);

  file_menu = IupMenu(
    item_new,
    item_open,
    item_save,
    item_saveas,
    item_revert,
    IupSeparator(),
    IupSubmenu("Recent &Files", recent_menu),
    item_exit,
    NULL);
  edit_menu = IupMenu(
    item_cut,
    item_copy,
    item_paste,
    item_delete,
    IupSeparator(),
    item_find,
    item_goto,
    IupSeparator(),
    item_select_all,
    NULL);
  format_menu = IupMenu(
    item_font,
    NULL);
  view_menu = IupMenu(
    item_toolbar,
    item_statusbar,
    NULL);
  help_menu = IupMenu(
    item_about,
    NULL);

  IupSetCallback(file_menu, "OPEN_CB", (Icallback)file_menu_open_cb);
  IupSetCallback(edit_menu, "OPEN_CB", (Icallback)edit_menu_open_cb);

  sub_menu_file = IupSubmenu("&File", file_menu);
  sub_menu_edit = IupSubmenu("&Edit", edit_menu);
  sub_menu_format = IupSubmenu("F&ormat", format_menu);
  sub_menu_view = IupSubmenu("&View", view_menu);
  sub_menu_help = IupSubmenu("&Help", help_menu);

  menu = IupMenu(
    sub_menu_file,
    sub_menu_edit,
    sub_menu_format,
    sub_menu_view,
    sub_menu_help,
    NULL);

  vbox = IupVbox(
    toolbar_hb,
    multitext,
    lbl_statusbar,
    NULL);

  dlg = IupDialog(vbox);
  IupSetAttributeHandle(dlg, "MENU", menu);
  IupSetAttribute(dlg, "SIZE", "HALFxHALF");
  IupSetCallback(dlg, "CLOSE_CB", (Icallback)item_exit_action_cb);
  IupSetCallback(dlg, "DROPFILES_CB", (Icallback)dropfiles_cb);

  IupSetAttribute(dlg, "CONFIG", (char*)config);

  /* parent for pre-defined dialogs in closed functions (IupMessage) */
  IupSetAttributeHandle(NULL, "PARENTDIALOG", dlg);

  IupSetCallback(dlg, "K_cN", (Icallback)item_new_action_cb);
  IupSetCallback(dlg, "K_cO", (Icallback)item_open_action_cb);
  IupSetCallback(dlg, "K_cS", (Icallback)item_save_action_cb);
  IupSetCallback(dlg, "K_cF", (Icallback)item_find_action_cb);
  IupSetCallback(dlg, "K_cG", (Icallback)item_goto_action_cb);
  
  IupConfigRecentInit(config, recent_menu, config_recent_cb, 10);

  IupConfigDialogShow(config, dlg, "MainWindow");

  /* initialize the current file */
  new_file(dlg);

  /* open a file from the command line (allow file association in Windows) */
  if (argc > 1 && argv[1])
  {
    const char* filename = argv[1];
    open_file(dlg, filename);
  }

  IupMainLoop();

  IupClose();
  return EXIT_SUCCESS;
}
Example #5
0
void
handle_NO_SYNC(float val)
{
  int a;
  float v, p;
  static int idx = 0, cnt = 0;
  static float sum = 0;
  static float buf[10] = { 0.0, };

  v = 0;
  for (a = 0;a < 10;a++)
    v += buf[a];
  v /= 10;

  buf[idx++] = val;
  if (idx >= 10)
    idx = 0;

  p = (100.0 * (v - val)) / v;

  if ((p > 30.0) || (p < -30))
    {
      cnt = 0;
      sum = 0;
    }
  else
    {
      cnt++;
      sum += val;
    }

  if (v > 20 * _lock)
    new_file();
    
  if (_verbose > 1)
    printf("NO SYNC: %6.2f, %6.2f, %10.2f, %d\n", val, v, p, cnt);

  if (cnt > 1000)
    {
      idx = 0;
      cnt = 0;
      for (a = 0;a < 10;a++)
	buf[a] = 0.0;

      _lock = sum / 1000;
      printf(".");
      fflush(stdout);      
      if (_verbose > 1)
	printf("LOCK: %.2f\n", _lock);
      set_state(STATE_SYNC);
    }

#if 0
  if ((4 * val) < 80)
    {
      for (a = 0;a < (4 * v);a++)
	printf(" ");
      printf("#\n");
    }
#endif
}
Example #6
0
bool App::event_keydown(WPARAM wParam){
	if(wParam==VK_ESCAPE){
        if(Config::geti()->fullscreen_on){ //wyjœcie z fullscreena
            fullscreen_set(false);
        }else{
            Controls::geti()->set_focus("editor");
        }
	}else if(wParam==VK_F1){
		set_scroll(0);
	}else if(wParam==VK_F2){
		change_scroll(-35);
	}else if(wParam==VK_F3){
		change_scroll(+35);
	}else if(wParam==VK_F5){
		autoscroll_nowait(+Config::geti()->autoscroll_interval*0.25);
	}else if(wParam==VK_F6){
		autoscroll_nowait(-Config::geti()->autoscroll_interval*0.2);
	}else if(wParam==VK_F7){
		autoscroll_switch();
	}else if(wParam==VK_F8){
		if(Config::geti()->autoscroll){
			autoscroll_off();
			IO::geti()->echo("Autoscroll wy³¹czony");
		}else{
			autoscroll_nowait();
		}
	}else if(wParam==VK_F9){
		toolbar_switch();
	}else if(wParam==VK_F10 || wParam==VK_F11){
        fullscreen_toggle();
	}
    //ctrl
	if(is_control_pressed()){
		if(wParam=='S'){
			save_chords_file();
		}else if(wParam=='F'){
            if(!Config::geti()->toolbar_show){
                toolbar_switch(1);
            }
			Controls::geti()->set_focus("find_edit");
		}else if(wParam=='N'){
            new_file();
        }else if(wParam=='B'){
            chordsbase_start();
        }else if(wParam==VK_ADD){
			change_font_size(+1);
		}else if(wParam==VK_SUBTRACT){
			change_font_size(-1);
		}else if(wParam==VK_OEM_3){ // znaczek `
            cmd_switch();
            if(Config::geti()->cmd_show){
                Controls::geti()->set_focus("cmd");
                Controls::geti()->select_all("cmd");
            }else{
                Controls::geti()->set_focus("editor");
            }
		}else if(wParam==VK_LEFT){
			transpose(-1);
		}else if(wParam==VK_RIGHT){
			transpose(+1);
		}else if(wParam=='0'||wParam==VK_NUMPAD0){
			transpose(-Config::geti()->transposed);
		}
	}
    return true; //przechwycenie
}
void FileHandler::concat_to_existing_file(string out_path, char* buffer, int buf_len) {
	ofstream new_file (out_path.c_str(),ofstream::binary | ofstream::app);
	new_file.write(buffer, buf_len);
	new_file.close();
}
Example #8
0
int FAT::open(const char *path)
{
    //  check if already open
    for (auto it = m_opened_files.begin(); it != m_opened_files.end(); ++it)
    {
        if (it->second.path == path)
            return -1;
    }

    OpenedFile of;
    int block = m_root->get_first_block();
    unsigned int size = m_root->get_size();
    unsigned char buffer[BLOCK_SIZE];

    // check if exists
    while (true)
    {
        ::lseek(m_fd, DATA_OFFSET + block*BLOCK_SIZE, SEEK_SET);
        unsigned int read_size = (size > BLOCK_SIZE) ? BLOCK_SIZE : size;
        if (::read(m_fd, buffer, BLOCK_SIZE) != BLOCK_SIZE)
            return -1;

        for (unsigned int i = 0; i < read_size; i += DirectoryEntry::DIRECTORY_ENTRY_SIZE)
        {
            DirectoryEntry file(buffer + i);
            if (string(path).substr(0, 8) == file.get_name())
            {
                of = { path, 0, file.get_first_block(), file.get_first_block(), file.get_size() };
                return get_next_file_descriptor(of);
            }
        }

        block = m_table[block];
        if (block == -1)
            break;

        size -= BLOCK_SIZE;
    }

    // Create if not exists
    int file_block = get_next_free_block();
    DirectoryEntry new_file(false, path, file_block, 0);

    // Write changes to directory
    if (size == BLOCK_SIZE)
    {
        int new_block = get_next_free_block();
        m_table[block] = new_block;
        ::lseek(m_fd, DATA_OFFSET + new_block*BLOCK_SIZE, SEEK_SET);
        size = 0;
    }
    else
        ::lseek(m_fd, -static_cast<int>(BLOCK_SIZE), SEEK_CUR);

    new_file.get_data(buffer + size);
    if (::write(m_fd, buffer, BLOCK_SIZE) != BLOCK_SIZE)
        return -1;

    // Create empty file
    memset(buffer, 0, BLOCK_SIZE);
    ::lseek(m_fd, DATA_OFFSET + file_block*BLOCK_SIZE, SEEK_SET);
    if (::write(m_fd, buffer, BLOCK_SIZE) != BLOCK_SIZE)
        return -1;

    m_root->increase_size(DirectoryEntry::DIRECTORY_ENTRY_SIZE);
    if (!update_fs_structs())
        return -1;

    of = { path, 0, file_block, file_block, 0 };
    return get_next_file_descriptor(of);
}
Example #9
0
void menu_items_treatment (GtkWidget *Widget, guint Op)
{
  gint CurrentPage, i;

  CurrentPage = gtk_notebook_get_current_page (GTK_NOTEBOOK(MainNotebook));
  switch(Op)
    {
    case NEW                  : new_file ();                   break;
    case OPEN                 : open_file ();                  break;
    case SAVE                 : save_file ();                  break;
    case SAVE_ALL             : save_all ();                   break;
    case SAVE_AS              : save_file_as ();               break;
    case PRINT                : print_buffer ();               break;
    case CLOSE                : close_file ();                 break;
    case CLOSE_ALL            : close_all ();                  break;
    case QUIT                 : quit ();                       break;
    case UNDO                 :
      if (OpenedFilesCnt)
	{
	  proceed_undo ();
	  break;
	 } 
    case REDO                 :
      if (OpenedFilesCnt)
	{
	  proceed_redo ();
	  break;
	}
    case CUT                  :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  gtk_editable_cut_clipboard (GTK_EDITABLE(FPROPS(CurrentPage, Text)));
	  print_msg ("Selection cut to Clipboard...");
	}
      break;
    case COPY                 :
      if (OpenedFilesCnt)
	{
	  gtk_editable_copy_clipboard
	    (GTK_EDITABLE(FPROPS(CurrentPage, Text)));
	  print_msg ("Selection copied to Clipboard...");
	}
	break;
    case PASTE                :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  gtk_editable_paste_clipboard
	    (GTK_EDITABLE(FPROPS(CurrentPage, Text)));
	  print_msg ("Text pasted from Clipboard...");
	}
      break;
    case CLEAR                :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  gtk_editable_delete_text
	    (GTK_EDITABLE(FPROPS(CurrentPage, Text)), 0, -1);
	  print_msg ("Buffer cleared...");
	}
      break;
    case SELECT_ALL           :
      if (OpenedFilesCnt)
	{
	  gtk_editable_select_region
	    (GTK_EDITABLE(FPROPS(CurrentPage, Text)), 0, -1);
	  print_msg ("All Text selected...");
	}
      break;
    case COMPLETE             :
      if (OpenedFilesCnt)
	auto_completion (GTK_TEXT(FPROPS(CurrentPage, Text)));
      break;
    case FIND                 :
      if (OpenedFilesCnt)
	search (FALSE);
      break;
    case REPLACE              :
      if (OpenedFilesCnt)
	search (TRUE);
      break;
    case LINE                 :
      if (OpenedFilesCnt)
	goto_line ();
      break;
    case READONLY             : toggle_readonly ();            break;
    case CONVERTER            : converter ();                  break;
    case COLOR                : color_picker ();               break;
    case INSERT_TIME          : insert_time (CurrentPage);     break;
    case TO_UPPER             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  change_case (1);
	  print_msg ("Selection converted to upper Case...");
	}
      break;
    case TO_LOWER             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  change_case (2);
	  print_msg ("Selection converted to Lower Case...");
	}
      break;
    case CAPITALIZE           :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  change_case (3);
	  print_msg ("Selection Capitalized...");
	}
      break; 
    case INVERT_CASE          :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  change_case (4);
	  print_msg ("Case inverted...");
	}
      break;
    case UNIX_DOS             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_unix_to_dos ();
	}
      break;
    case UNIX_MAC             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_unix_to_mac ();
	}
      break;
    case DOS_UNIX             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_dos_to_unix ();
	}
      break;
    case DOS_MAC              :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_dos_to_mac ();
	}
      break;
    case MAC_DOS              :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_mac_to_dos ();
	}
      break;
    case MAC_UNIX             :
      if ((OpenedFilesCnt) && !FPROPS(CurrentPage, ReadOnly))
	{
	  conv_mac_to_unix ();
	}
      break;
    case UNIX_DOS_ALL             :
      convert_all(conv_unix_to_dos);
      break;
    case UNIX_MAC_ALL             :
      convert_all(conv_unix_to_mac);
      break;
    case DOS_UNIX_ALL             :
      convert_all(conv_dos_to_unix);
      break;
    case DOS_MAC_ALL              :
      convert_all(conv_dos_to_mac);
      break;
    case MAC_DOS_ALL              :
      convert_all(conv_mac_to_dos);
      break;
    case MAC_UNIX_ALL             :
      convert_all(conv_mac_to_unix);
      break;
    case FILE_INFO            : file_info (CurrentPage);       break;
    case TOOLBAR              :
      if ((!ToolBarToggleDisplay) && (TOOLBAR_DISPLAY))
	ToolBarToggleDisplay = TRUE;
      else
	{
	  if (TOOLBAR_DISPLAY)
	    {
	      TOOLBAR_DISPLAY = FALSE;
	      hide_toolbar ();
	      print_msg ("Hide Tool Bar...");
	    }
	  else
	    {
	      TOOLBAR_DISPLAY = TRUE;
	      show_toolbar ();
	      if (!ToolBarToggleDisplay) ToolBarToggleDisplay = TRUE;
	      print_msg ("Display Tool Bar...");
	    }
	}
      break;
    case MSGBAR               :
      if ((!MsgBarToggleDisplay) && (MSGBAR_DISPLAY))
	MsgBarToggleDisplay = TRUE;
      else
	{
	  if (MSGBAR_DISPLAY)
	    {
	      MSGBAR_DISPLAY = FALSE;
	      hide_msgbar ();
	    }
	  else
	    {
	      MSGBAR_DISPLAY = TRUE;
	      show_msgbar ();
	      if (!MsgBarToggleDisplay) MsgBarToggleDisplay = TRUE;
	      print_msg ("Display Msg Bar...");
	    }
	}
      break;
    case WORDWRAP        :
     if ((!ToggleWordwrap) && (TOGGLE_WORDWRAP))
	ToggleWordwrap = TRUE;
      else
	{
	  if (TOGGLE_WORDWRAP)
	    {
	      TOGGLE_WORDWRAP = FALSE;
	      for (i = 0; i < OpenedFilesCnt; i++)
		gtk_text_set_word_wrap (GTK_TEXT(FPROPS(CurrentPage, Text)),
					FALSE);
	      print_msg ("Wordwrap disabled...");
	    }
	  else
	    {
	      TOGGLE_WORDWRAP = TRUE;
	      for (i = 0; i < OpenedFilesCnt; i++)
		gtk_text_set_word_wrap (GTK_TEXT(FPROPS(CurrentPage, Text)),
					TRUE);
	      if (!ToggleWordwrap) ToggleWordwrap = TRUE;
	      print_msg ("Wordwrap enabled...");
	    }
	}
      break;
    case TAB_POS_TOP          :
      TAB_POSITION = 1;
      gtk_notebook_set_tab_pos (GTK_NOTEBOOK(MainNotebook), GTK_POS_TOP);
      break;
    case TAB_POS_BOTTOM       :
      TAB_POSITION = 2;
      gtk_notebook_set_tab_pos (GTK_NOTEBOOK(MainNotebook), GTK_POS_BOTTOM);
      break;
    case TAB_POS_LEFT         :
      TAB_POSITION = 3;
      gtk_notebook_set_tab_pos (GTK_NOTEBOOK(MainNotebook), GTK_POS_LEFT);
      break;
    case TAB_POS_RIGHT        :
      TAB_POSITION = 4;
      gtk_notebook_set_tab_pos (GTK_NOTEBOOK(MainNotebook), GTK_POS_RIGHT);  
      break;
    case SCROLLBAR_POS_LEFT   :
      SCROLLBAR_POSITION = 1;
      for (i = 0; i < OpenedFilesCnt; i++)
	gtk_scrolled_window_set_placement (GTK_SCROLLED_WINDOW
					   (gtk_notebook_get_nth_page
					    (GTK_NOTEBOOK(MainNotebook), i)),
					   GTK_CORNER_TOP_RIGHT);
      break;
    case SCROLLBAR_POS_RIGHT  :
      SCROLLBAR_POSITION = 2;
      for (i = 0; i < OpenedFilesCnt; i++)
	gtk_scrolled_window_set_placement (GTK_SCROLLED_WINDOW
					   (gtk_notebook_get_nth_page
					    (GTK_NOTEBOOK(MainNotebook), i)),
					   GTK_CORNER_TOP_LEFT);
      break;
    case PREFS                : display_prefs (&Settings);     break;
    case HELP                 :
      print_msg ("No help available yet...");
      break;
    case ABOUT                : about ();                      break;
    }
  (void)Widget; /* avoid the "unused parameter" warning */
}
Example #10
0
codeWindow::codeWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::codeWindowClass)
{
    codePage = "CP866";
    ui->setupUi(this);
    ui->tabWidget->clear();
    QWidget *back = new QWidget();
    QWidget *pole = new QWidget();
    QHBoxLayout *hbox = new QHBoxLayout(pole);
    listingBrowser = new QTextEdit();
    listingBrowser->setReadOnly(true);
    textEdit = new QTextEdit();
    ln = new LineNumbers(textEdit);
    hbox->addWidget(ln);
    hbox->addWidget(textEdit);
    splitter = new QSplitter(Qt::Vertical,back);
    textBrowser = new QTextEdit();
    textBrowser->setReadOnly(true);
    splitter->addWidget(pole);
    splitter->addWidget(textBrowser);
    //QHBoxLayout *hboxb = new QHBoxLayout(back);
    back->setLayout(new QHBoxLayout());
    back->layout()->addWidget(splitter);
    pushButton = new QPushButton(trUtf8("Компиляция"),this);
    pushButton_2 = new QPushButton(trUtf8("Линковка"),this);
    pushButton_3 = new QPushButton(trUtf8("Запуск"),this);
    pushButton_4 = new QPushButton(trUtf8("Отмена\nоперации"),this);
    pushButton_5 = new QPushButton(trUtf8("Отладчик"),this);
    pushButton_4->setEnabled(false);
    ui->mainToolBar->addWidget(pushButton);
    ui->mainToolBar->addWidget(pushButton_2);
    ui->mainToolBar->addWidget(pushButton_3);
    ui->mainToolBar->addWidget(pushButton_5);
    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addWidget(pushButton_4);
    pushButton->setIcon(this->style()->standardIcon(QStyle::SP_ArrowForward));
    ui->action_tasm->setIcon(pushButton->icon());
    pushButton_2->setIcon(this->style()->standardIcon(QStyle::SP_ArrowDown));
    ui->action_tlink->setIcon(pushButton_2->icon());
    pushButton_3->setIcon(this->style()->standardIcon(QStyle::SP_MediaPlay));
    ui->action_run->setIcon(pushButton_3->icon());
    pushButton_4->setIcon(this->style()->standardIcon(QStyle::SP_BrowserStop));
    ui->action_cansel->setIcon(pushButton_4->icon());
    pushButton_5->setIcon(this->style()->standardIcon(QStyle::SP_ComputerIcon));
    ui->action_td->setIcon(pushButton_5->icon());
    ui->action->setIcon(this->style()->standardIcon(QStyle::SP_DialogOpenButton));
    ui->action_2->setIcon(this->style()->standardIcon(QStyle::SP_DialogSaveButton));
    ui->action_3->setIcon(this->style()->standardIcon(QStyle::SP_DialogSaveButton));
    ui->action_4->setIcon(this->style()->standardIcon(QStyle::SP_TitleBarCloseButton));
    ui->action_5->setIcon(this->style()->standardIcon(QStyle::SP_DesktopIcon));
    ui->action_6->setIcon(this->style()->standardIcon(QStyle::SP_DialogHelpButton));
    ui->action_13->setIcon(this->style()->standardIcon(QStyle::SP_FileIcon));
    ui->action_TASM->setIcon(this->style()->standardIcon(QStyle::SP_TrashIcon));
    set = new settingsClass(this);
    splitter->restoreState(set->getValue("splitter").toByteArray());
    this->restoreState(set->getValue("state").toByteArray());
    this->ui->action_10->setChecked(set->getValue("statusBar").toBool());
    this->ui->action_9->setChecked(ui->mainToolBar->isEnabled());
    curpos = new QLabel("1 : 1",this);
    ui->statusBar->layout()->setAlignment(Qt::AlignRight);
    ui->statusBar->layout()->addWidget(curpos);
    ui->action_9->setChecked(!ui->mainToolBar->isHidden());
    connect(textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(curPosChanged()));
    connect(this->ui->action_5,SIGNAL(triggered()),this,SLOT(colorSet()));
    connect(this->ui->action_TASM,SIGNAL(triggered()),this,SLOT(asmSett()));
    connect(this->ui->action_QT,SIGNAL(triggered()),this,SLOT(aboutQt()));
    connect(this->ui->action_4,SIGNAL(triggered()),this,SLOT(close()));
    connect(this->ui->action,SIGNAL(triggered()),this,SLOT(open()));
    connect(this->ui->action_2,SIGNAL(triggered()),this,SLOT(save()));
    connect(this->ui->action_13,SIGNAL(triggered()),this,SLOT(new_file()));
    connect(this->ui->action_3,SIGNAL(triggered()),this,SLOT(saveAs()));
    connect(this->ui->action_6,SIGNAL(triggered()),this,SLOT(about()));
    connect(this->ui->action_9,SIGNAL(triggered(bool)),ui->mainToolBar,SLOT(setShown(bool)));
    connect(this->ui->action_10,SIGNAL(triggered(bool)),ui->statusBar,SLOT(setShown(bool)));
    connect(pushButton,SIGNAL(released()),this,SLOT(pushButton_released()));
    connect(pushButton_2,SIGNAL(released()),this,SLOT(pushButton_2_released()));
    connect(pushButton_3,SIGNAL(released()),this,SLOT(pushButton_3_released()));
    connect(pushButton_4,SIGNAL(released()),this,SLOT(pushButton_4_released()));
    connect(pushButton_5,SIGNAL(released()),this,SLOT(pushButton_5_released()));
    connect(ui->action_tasm,SIGNAL(triggered()),pushButton,SLOT(click()));
    connect(ui->action_tlink,SIGNAL(triggered()),pushButton_2,SLOT(click()));
    connect(ui->action_run,SIGNAL(triggered()),pushButton_3,SLOT(click()));
    connect(ui->action_cansel,SIGNAL(triggered()),pushButton_4,SLOT(click()));
    connect(ui->action_td,SIGNAL(triggered()),pushButton_5,SLOT(click()));
    connect(ui->tabWidget,SIGNAL(currentChanged(int)),this,SLOT(listingLoad(int)));
    foreach(QString s,QTextCodec::availableCodecs())
    {
        QAction *a = new QAction(s,this);
        ui->menu_4->addAction(a);
    }
Example #11
0
static int k_any(Ihandle *ih, int c)
{
    switch(c)
    {
    case K_m:
        IupSetGlobal("PARENTDIALOG", "_MAIN_DIALOG_TEST_");
        IupMessage("IupMessage Test", "Message Text\nSecond Line.");
        IupSetGlobal("PARENTDIALOG", NULL);
        break;
    case K_e:
        new_message("ERROR", NULL);
        break;
    case K_i:
        new_message("INFORMATION", NULL);
        break;
    case K_w:
        new_message("WARNING", "OKCANCEL");
        break;
    case K_q:
        new_message("QUESTION", "YESNO");
        break;
    case K_c:
        new_color();
        break;
    case K_f:
        new_font();
        break;
    case K_o:
        new_file("OPEN", 0);
        break;
    case K_O:
        new_file("OPEN", 1);
        break;
    case K_G:
        new_file("OPEN", 2);
        break;
    case K_s:
        new_file("SAVE", 0);
        break;
    case K_d:
        new_file("DIR", 0);
        break;
    case K_a:
        new_alarm();
        break;
    case K_y:
        IupShow(IupLayoutDialog(NULL));
        break;
    case K_g:
        new_getfile();
        break;
    case K_t:
        new_gettext();
        break;
    case K_l:
        new_list();
        break;
    case K_ESC:
        IupDestroy(ih);
        return IUP_IGNORE;
    }
    return IUP_DEFAULT;
}
Example #12
0
int main_TrainingTagger(int argc,char* const argv[]) {
if (argc==1) {
   usage();
   return 0;
}

int val,index=-1,binaries=1,r_forms=1,i_forms=1;
int semitic=0;
struct OptVars* vars=new_OptVars();
char text[FILENAME_MAX]="";
char raw_forms[FILENAME_MAX]="";
char inflected_forms[FILENAME_MAX]="";
char output[FILENAME_MAX]="";
Encoding encoding_output = DEFAULT_ENCODING_OUTPUT;
int bom_output = DEFAULT_BOM_OUTPUT;
int mask_encoding_compatibility_input = DEFAULT_MASK_ENCODING_COMPATIBILITY_INPUT;
while (EOF!=(val=getopt_long_TS(argc,argv,optstring_TrainingTagger,lopts_TrainingTagger,&index,vars))) {
   switch(val) {
   case 'o': if (vars->optarg[0]=='\0') {
                fatal_error("You must specify a non empty pattern\n");
             }
             strcpy(output,vars->optarg);
             break;
   case 'b': binaries = 1;
			 break;
   case 'n': binaries = 0;
			 break;
   case 'a': break;
   case 'c': i_forms = 0;
			 break;
   case 'm': r_forms = 0;
   			 break;
   case 'S': semitic=1;
   			 break;
   case 'k': if (vars->optarg[0]=='\0') {
                fatal_error("Empty input_encoding argument\n");
             }
             decode_reading_encoding_parameter(&mask_encoding_compatibility_input,vars->optarg);
             break;
   case 'q': if (vars->optarg[0]=='\0') {
                fatal_error("Empty output_encoding argument\n");
             }
             decode_writing_encoding_parameter(&encoding_output,&bom_output,vars->optarg);
             break;
   case 'h': usage(); return 0;
   case ':': if (index==-1) fatal_error("Missing argument for option -%c\n",vars->optopt);
             else fatal_error("Missing argument for option --%s\n",lopts_TrainingTagger[index].name);
   case '?': if (index==-1) fatal_error("Invalid option -%c\n",vars->optopt);
             else fatal_error("Invalid option --%s\n",vars->optarg);
             break;
   }
   index=-1;
}

if (vars->optind!=argc-1) {
   free_OptVars(vars);
   error("Invalid arguments: rerun with --help\n");
   return 1;
}
strcpy(text,argv[vars->optind]);
U_FILE* input_text=u_fopen_existing_versatile_encoding(mask_encoding_compatibility_input,text,U_READ);
if (input_text==NULL) {
   free_OptVars(vars);
   fatal_error("cannot open file %s\n",text);
   return 1;
}

if(output[0]=='\0'){
	remove_path_and_extension(text,output);
}

char path[FILENAME_MAX],filename[FILENAME_MAX];
get_path(text,path);
if(strlen(path) == 0){
	strcpy(path,".");
}
/* we create files which will contain statistics extracted from the tagged corpus */
U_FILE* rforms_file = NULL, *iforms_file = NULL;
if(r_forms == 1){
	sprintf(filename,"%s_data_cat.dic",output);
	new_file(path,filename,raw_forms);
	rforms_file=u_fopen_creating_versatile_encoding(encoding_output,bom_output,raw_forms,U_WRITE);
}
if(i_forms == 1){
	sprintf(filename,"%s_data_morph.dic",output);
	new_file(path,filename,inflected_forms);
	iforms_file=u_fopen_creating_versatile_encoding(encoding_output,bom_output,inflected_forms,U_WRITE);
}

u_printf("Gathering statistics from tagged corpus...\n");
do_training(input_text,rforms_file,iforms_file);

/* we close all files and then we sort text dictionaries */
u_fclose(input_text);
char disclaimer[FILENAME_MAX];
if(rforms_file != NULL){
	u_fclose(rforms_file);
	pseudo_main_SortTxt(DEFAULT_ENCODING_OUTPUT,DEFAULT_BOM_OUTPUT,ALL_ENCODING_BOM_POSSIBLE,0,0,NULL,NULL,0,raw_forms);
	strcpy(disclaimer,raw_forms);
	remove_extension(disclaimer);
	strcat(disclaimer,".txt");
	create_disclaimer(disclaimer);
}
if(iforms_file != NULL){
	u_fclose(iforms_file);
	pseudo_main_SortTxt(DEFAULT_ENCODING_OUTPUT,DEFAULT_BOM_OUTPUT,ALL_ENCODING_BOM_POSSIBLE,0,0,NULL,NULL,0,inflected_forms);
	strcpy(disclaimer,inflected_forms);
	remove_extension(disclaimer);
	strcat(disclaimer,".txt");
	create_disclaimer(disclaimer);
}

/* we compress dictionaries if option is specified by user (output is ".bin") */
if(binaries == 1){
/* simple forms dictionary */
if(r_forms == 1){
	pseudo_main_Compress(DEFAULT_ENCODING_OUTPUT,DEFAULT_BOM_OUTPUT,ALL_ENCODING_BOM_POSSIBLE,0,semitic,raw_forms);
}
/* compound forms dictionary */
if(i_forms == 1){
	pseudo_main_Compress(DEFAULT_ENCODING_OUTPUT,DEFAULT_BOM_OUTPUT,ALL_ENCODING_BOM_POSSIBLE,0,semitic,inflected_forms);
}
}
free_OptVars(vars);
u_printf("Done.\n");
return 0;
}
Example #13
0
SIGNAL_CALLBACK void on_new_button_clicked(GtkWidget *w)
{
    new_file();
}
Example #14
0
/* callback function */
void mainwnd::file_new()
{
    if (is_save())
        new_file();
}
void FileHandler::create_file_from_buf(string out_path, char* buffer, int buf_len) {
	cout<<"PATH "<<out_path<<endl;
	ofstream new_file (out_path.c_str(),ofstream::binary);
	new_file.write(buffer, buf_len);
	new_file.close();
}
Example #16
0
bool load_4d_nii(const char* file_name,boost::ptr_vector<DwiHeader>& dwi_files)
{
    gz_nifti analyze_header;
    if(!analyze_header.load_from_file(file_name))
        return false;
    std::cout << "loading 4d nifti" << std::endl;


    std::vector<double> bvals,bvecs;
    {
        QString bval_name,bvec_name;
        bval_name = QFileInfo(file_name).absolutePath() + "/bvals";
        if(!QFileInfo(bval_name).exists())
            bval_name = QFileInfo(file_name).absolutePath() + "/bvals.txt";

        bvec_name = QFileInfo(file_name).absolutePath() + "/bvecs";
        if(!QFileInfo(bvec_name).exists())
            bvec_name = QFileInfo(file_name).absolutePath() + "/bvecs.txt";


        if(QFileInfo(bval_name).exists() && QFileInfo(bvec_name).exists())
        {
            load_bval(bval_name.toLocal8Bit().begin(),bvals);
            load_bvec(bvec_name.toLocal8Bit().begin(),bvecs);
            if(analyze_header.dim(4) != bvals.size() ||
               bvals.size()*3 != bvecs.size())
            {
                bvals.clear();
                bvecs.clear();
            }
            else
                std::cout << "bvals and bvecs loaded" << std::endl;
        }

    }

    image::basic_image<float,4> grad_dev;
    image::basic_image<unsigned char,3> mask;
    if(QFileInfo(QFileInfo(file_name).absolutePath() + "/grad_dev.nii.gz").exists())
    {
        gz_nifti grad_header;
        if(grad_header.load_from_file(QString(QFileInfo(file_name).absolutePath() + "/grad_dev.nii.gz").toLocal8Bit().begin()))
        {
            grad_header.toLPS(grad_dev);
            std::cout << "grad_dev used" << std::endl;
        }
    }
    if(QFileInfo(QFileInfo(file_name).absolutePath() + "/nodif_brain_mask.nii.gz").exists())
    {
        gz_nifti mask_header;
        if(mask_header.load_from_file(QString(QFileInfo(file_name).absolutePath() + "/nodif_brain_mask.nii.gz").toLocal8Bit().begin()))
        {
            mask_header.toLPS(mask);
            std::cout << "mask used" << std::endl;
        }
    }
    {
        float vs[4];
        analyze_header.get_voxel_size(vs);
        for(unsigned int index = 0;check_prog(index,analyze_header.dim(4));++index)
        {
            std::auto_ptr<DwiHeader> new_file(new DwiHeader);
            if(!analyze_header.toLPS(new_file->image,false))
                break;
            image::lower_threshold(new_file->image,0);
            new_file->file_name = file_name;
            std::ostringstream out;
            out << index;
            new_file->file_name += out.str();
            std::copy(vs,vs+3,new_file->voxel_size);
            if(!bvals.empty())
            {
                new_file->bvalue = bvals[index];
                new_file->bvec[0] = bvecs[index*3];
                new_file->bvec[1] = bvecs[index*3+1];
                new_file->bvec[2] = bvecs[index*3+2];
                new_file->bvec.normalize();
                if(new_file->bvalue < 10)
                {
                    new_file->bvalue = 0;
                    new_file->bvec = image::vector<3>(0,0,0);
                }
            }
            if(index == 0 && !grad_dev.empty())
                new_file->grad_dev.swap(grad_dev);
            if(index == 0 && !mask.empty())
                new_file->mask.swap(mask);
            dwi_files.push_back(new_file.release());
        }
    }

    return true;
}
Example #17
0
    bool insert_active( const char *new_name )
    {
        bool return_value = false;
        YEditFile     &old_entry = active_file();
        YEditFile     *new_entry;
        FilePosition old_CP = old_entry.CP();

        // If we are trying to insert this file into itself, do nothing.
        if( my_stricmp( old_entry.name(), new_name ) == 0 ) {
            return true;
        }

        // If a file with the new name exists, make it the active one.
        if( lookup( new_name ) == true ) {
            new_entry = *the_list.get( );
            return_value = true;
        }

        // No such file, try to create/load one.
        else if( new_file(new_name ) == true ) {
            new_entry = *the_list.get( );
            return_value = true;
        }

        // If I've got a target file, then transfer the text.
        if( return_value == true ) {
            long top;
            long bottom;
            bool old_state = old_entry.get_block_state( );

            // If the old file didn't have block mode on, then block entire file.
            if( old_state == false ) {
                old_entry.top_of_file( );
                old_entry.toggle_block( );
                old_entry.bottom_of_file( );
            }
            old_entry.block_limits( top, bottom );
            old_entry.CP( ).jump_to_line( top );

            // Adjust bottom if entire file is blocked.
            bottom = ( old_state == true ) ? bottom : bottom - 1;

            // Copy the text of the original file into the new file.
            for( long line_number = top;
                 return_value == true && line_number <= bottom;
                 line_number++) {
                if( new_entry->insert_line( old_entry.get_line( ) ) == false ) {
                    error_message( "Unable to completely build new file object" );
                    return_value = false;
                }
                else {
                    new_entry->CP( ).cursor_down( );
                    old_entry .CP( ).jump_to_line( line_number + 1 );
                }
            }
            old_entry.CP( ) = old_CP;

            // If the old file had block mode on, delete the block.
            if( old_state == true ) old_entry.delete_block( );

            // In any case, turn off the block mode.
            old_entry.toggle_block( );
        }

        return return_value;
    }
Example #18
0
int main(int num_arg, char *argv[])
{
	try
	{
		//						Read function arguments
		//----------------------------------------------------------------------
		bool use_config_file = 0, enable_logfile = 0;
		string filename;


		if (num_arg < 2);
		else if ( string(argv[1]) == "--help")
		{
			printf("\n\t       Arguments of the function 'main' \n");
			printf("==============================================================\n\n");
			printf(" --help: Shows this menu... \n\n");
			printf(" --config FICH.txt: Load FICH.txt as config file \n\n");
			printf(" --create-config FICH.txt: Save the default config parameters \n\n");
			printf(" \t\t\t   in FICH.txt and close the program \n\n");
			printf(" --save-logfile: Enable saving a log file with navigation data \n\n");
			system::os::getch();
			return 1;
		}
		else if ( string(argv[1]) == "--create-config")
		{
			filename = argv[2];
			cout << endl << "Nombre del archivo: " << filename;
			ofstream new_file(filename.c_str());
			new_file << string(default_cfg_txt);
			new_file.close();
			cout << endl << "File saved" << endl;
			system::os::getch();
			return 1;
		}
		else
		{
			for (int i=1; i<num_arg; i++)
			{
				if ( string(argv[i]) == "--save-logfile")
					enable_logfile = 1;

				if ( string(argv[i]) == "--config")
				{
					use_config_file = 1;
					filename = argv[i+1];
				}
			}
		}


		//Initial steps. Load configuration from file or default
		//------------------------------------------------------

		CMyReactInterface ReactInterface;
		CReactiveNavigationSystem3D rn3d (ReactInterface, true, enable_logfile);

		if (use_config_file == 0)
		{
			utils::CConfigFileMemory configNavigation(default_cfg_txt);
			rn3d.loadConfigFile( configNavigation );
			ReactInterface.loadMaps( configNavigation );
			ReactInterface.loadConfiguration( configNavigation );
		}
		else
		{
			CConfigFile configNavigation(filename);
			rn3d.loadConfigFile( configNavigation );
			ReactInterface.loadMaps( configNavigation );
			ReactInterface.loadConfiguration( configNavigation );
		}

		ReactInterface.initializeScene();
		rn3d.initialize();


		bool stop = 0;
		bool moving_target = 0;
		int pushed_key = 0;
		TPoint3D last_Target_Pos(0,0,0);
		CTicTac	reactive_period;
		reactive_period.Tic();

		MyObserver observer;
		observer.observeBegin(ReactInterface.window);
		observer.mouse_click = 0;


		while (!stop)
		{
			if (ReactInterface.window.keyHit())
				pushed_key = ReactInterface.window.getPushedKey();
			else
				pushed_key = 0;

			switch (pushed_key) {

			case  'p':
				//Pause navigation
				rn3d.suspend();
				break;

			case 'r':
				//Resume navigation
				rn3d.resume();
				break;

			case 'm':
				//Move the target
				moving_target = 1;
				break;

			case 'e':
				//Exit program
				stop = 1;
				break;

			}

			//Set the target when the user clicks the mouse
			if (observer.mouse_click == 1)
			{
				observer.mouse_click = 0;
				if (moving_target == 1)
				{
					moving_target = 0;
					const CAbstractReactiveNavigationSystem::TNavigationParams  nav_params = ReactInterface.createNewTarget(last_Target_Pos.x, last_Target_Pos.y, 0.3, 0);
					rn3d.navigate(&nav_params);
				}
			}

			//Execute navigation
			rn3d.navigationStep();
			ReactInterface.robotSim.simulateInterval( reactive_period.Tac() );
			reactive_period.Tic();

			if ((rn3d.IDLE == rn3d.getCurrentState())||(rn3d.SUSPENDED == rn3d.getCurrentState()))
			{
				CSimplePointsMap auxpoints;
				ReactInterface.senseObstacles( auxpoints );
			}
			ReactInterface.updateScene();
			system::sleep(5);


			//Move target with the mouse
			if (moving_target == 1)
			{
				int mouse_x,mouse_y;
				if (ReactInterface.window.getLastMousePosition(mouse_x,mouse_y))
				{
					// Get the ray in 3D for the latest mouse (X,Y):
					math::TLine3D ray;
					ReactInterface.scene->getViewport("main")->get3DRayForPixelCoord(mouse_x,mouse_y,ray);

					// Create a 3D plane, e.g. Z=0
					const math::TPlane ground_plane(TPoint3D(0,0,0),TPoint3D(1,0,0),TPoint3D(0,1,0));

					// Intersection of the line with the plane:
					math::TObject3D inters;
					math::intersect(ray,ground_plane, inters);

					// Interpret the intersection as a point, if there is an intersection:
					if (inters.getPoint(last_Target_Pos))
					{
						// Move an object to the position picked by the user:
						ReactInterface.scene->getByClass<CDisk>(0)->setLocation(last_Target_Pos.x, last_Target_Pos.y, last_Target_Pos.z);
					}
				}
			}

		}

		return 0;
	}
	catch (std::exception &e)
	{
		std::cout << "MRPT exception caught: " << e.what() << std::endl;
		return -1;
	}
	catch (...)
	{
		printf("Untyped exception!!");
		return -1;
	}
}
Example #19
0
//-----------------------------------------------------------------------------
// the SD card has been inserted, do the necessary steps to get a sane system
static int
on_insert(void)
{
	FRESULT stat;

	kbs_setFName(KUROBOX_LOADING_NAME);
	if (!sdcConnect(&SDCD1))
	{
		kbs_setFName(KUROBOX_ERR1);
		return KB_NOT_OK;
	}

	stat = f_mount(&SDC_FS, "/", 1);
	if (stat != FR_OK)
	{
		kbs_setFName(KUROBOX_ERR2);
		sdcDisconnect(&SDCD1);
		return KB_NOT_OK;
	}

	chThdSleepMilliseconds(100);
	uint32_t clusters;
	FATFS * fsp = NULL;
	stat = f_getfree("/", &clusters, &fsp);
	if (stat != FR_OK)
	{
		kbs_setFName(KUROBOX_ERR3);
		sdcDisconnect(&SDCD1);
		return KB_NOT_OK;
	}
	uint64_t cardsize = clusters * (((uint32_t)fsp->csize * (uint32_t)MMCSD_BLOCK_SIZE) / 1024);
	cardsize_MB = cardsize / 1024;

	// @TODO: this can be moved to above the check for free space
	fs_write_protected = sdc_lld_is_write_protected(&SDCD1);
	if ( fs_write_protected )
	{
		// -1 means that it's write protected, display that
		kbs_setSDCFree(-1);
		kbs_setFName(KUROBOX_WP_NAME);
		return KB_NOT_OK;
	}
	kbs_setSDCFree(cardsize_MB);

	stat = make_dirs();
	if (stat != FR_OK)
	{
		kbs_setFName(KUROBOX_ERR4);
		sdcDisconnect(&SDCD1);
		return KB_NOT_OK;
	}

	stat = new_file();
	if (stat != FR_OK)
	{
		kbs_setFName(KUROBOX_ERR5);
		sdcDisconnect(&SDCD1);
		return KB_NOT_OK;
	}

	fs_ready = TRUE;
	logger_state = LS_RUNNING;

	kbs_err_setSD(1);

	return KB_OK;
}
Example #20
0
void App::event_button(WPARAM wParam){
    string name = "";
    if(wParam>=1 && wParam<=Controls::geti()->controls.size()){
        name = Controls::geti()->get_button_name(wParam);
    }else{
        name = Controls::geti()->get_menu_name(wParam);
    }
    if(name.length()==0) return;
	if(name == "new"){ //nowy
		new_file();
	}else if(name == "load"){ //wczytaj
        if(!Config::geti()->toolbar_show){
            toolbar_switch(1);
        }
        string str2 = Controls::geti()->get_text("filename_edit");
		if(str2.length()==0){
			IO::geti()->echo("Podaj nazwê pliku.");
		}else{
			open_chords_file(str2);
		}
	}else if(name == "save"){ //zapisz
		save_chords_file();
	}else if(name == "analyze"){ //analizuj
		analyze();
	}else if(name == "replace"){ //zamieñ
        if(!Config::geti()->toolbar_show){
            toolbar_switch(1);
            return;
        }
		zamien();
	}else if(name == "find"){ //znajdŸ
        if(!Config::geti()->toolbar_show){
            toolbar_switch(1);
            return;
        }
		znajdz();
	}else if(name == "undo"){
        undo->revert();
	}else if(name == "base"){ //baza akordów
        chordsbase_start();
	}else if(name == "autoscroll"){ //autoscroll
		autoscroll_switch();
	}else if(name == "reload"){
        open_chords_file(Config::geti()->opened_file);
    }else if(name == "config"){
        ShellExecute(0,"open",Config::geti()->config_filename.c_str(),"",0,SW_SHOW);
    }else if(name == "quick_replace"){
        quick_replace();
    }else if(name == "remove_chords"){
        usun_akordy();
    }else if(name == "remove_alt"){
        usun_wersje();
    }else if(name == "add_chord"){
        dodaj_nawias();
    }else if(name == "font++"){
        change_font_size(+1);
    }else if(name == "font--"){
        change_font_size(-1);
    }else if(name == "format_text"){
        refresh_text();
    }else if(name == "fullscreen"){
        fullscreen_toggle();
    }else if(name == "autoscroll_wait"){
        autoscroll_on();
    }else if(name == "autoscroll_nowait"){
        autoscroll_nowait();
    }else if(name == "autoscroll_off"){
        autoscroll_off();
        IO::geti()->echo("Autoscroll wy³¹czony");
    }else if(name == "autoscroll_slower"){
        autoscroll_nowait(+Config::geti()->autoscroll_interval*0.25);
    }else if(name == "autoscroll_faster"){
        autoscroll_nowait(-Config::geti()->autoscroll_interval*0.2);
    }else if(name == "transpose+5"){
        transpose(+5);
    }else if(name == "transpose++"){
        transpose(+1);
    }else if(name == "transpose--"){
        transpose(-1);
    }else if(name == "transpose-5"){
        transpose(-5);
    }else if(name == "transpose0"){
        transpose(-Config::geti()->transposed);
    }else if(name == "alt"){
        dodaj_alternatywne();
    }else if(name == "log"){
        ShellExecute(0, "open", Config::geti()->log_filename.c_str(), "", 0, SW_SHOW);
    }else if(name == "associate_files"){
        associate_files();
    }else if(name == "help"){
        show_help();
    }else if(name == "info"){
        stringstream ss;
        ss<<Config::geti()->program_name<<endl;
        ss<<"wersja "<<version<<endl;
        IO::geti()->message_box("O programie",ss.str());
    }else if(name == "cmd_toggle"){
        cmd_switch();
    }else if(name == "toolbar_toggle"){
        toolbar_switch();
    }else if(name == "scroll_to_begin"){
        set_scroll(0);
    }else if(name == "scroll_to_end"){
        SendMessage(Controls::geti()->find("editor"), WM_VSCROLL, SB_BOTTOM, 0);
    }else if(name == "save_pattern"){
        save_pattern();
    }else if(name == "insert_pattern"){
        insert_pattern();
    }else if(name == "exit"){
        DestroyWindow(main_window);
    }else{
        IO::geti()->error("Zdarzenie nie zosta³o obs³u¿one: "+name);
    }
}
Example #21
0
//-----------------------------------------------------------------------------
// main writer thread function - is called when SD card is ready and we're just
// going to keep writing until SD card is ejected.
// @TODO: when file exceeds 1GB, start a new file
static uint8_t
writing_run(void)
{
	uint8_t ret = 1;
	uint32_t writer_buffers_written = 0;
	while(LS_RUNNING == logger_state)
	{
		if (chThdShouldTerminateX())
		{
			logger_state = LS_EXITING;
			f_sync(&kbfile);
			f_close(&kbfile);
			sdcDisconnect(&SDCD1);
			break;
		}

		int8_t idx = new_write_buffer_idx_to_write();
		if ( idx == -1 )
		{
			// no more buffers to write, go to sleep, wait to be notified
			chSysLock();
				writerThreadForSleep = chThdGetSelfX();
			    chSchGoSleepS(CH_STATE_SUSPENDED);
			chSysUnlock();

			// we can get woken up by either a buffer ready to be written
			// or a request to terminate, either way, back to the start
			// of the loop to check.
			continue;
		}

		//----------------------------------------------------------------------
		// start of write
		kbg_setLED1(1);

		// here we have a full buffer ready to write
		write_buffer_t * buf = &write_buffers[idx];

		UINT bytes_written = 0;
		FRESULT stat = FR_OK;

		DEBG_WRITER_TIME_WRITES_TIMER(0);
		stat = f_write(&kbfile, buf->buffer, sizeof(buf->buffer), &bytes_written);
		DEBG_WRITER_TIME_WRITES_TIMER(1);

		kbg_setLED1(0);
		// end of write
		//----------------------------------------------------------------------

		if (bytes_written != sizeof(buf->buffer) || stat != FR_OK)
			current_msg.write_errors++;

		//----------------------------------------------------------------------
		// start of flush
		//kbg_setLED2(1);
		
		DEBG_WRITER_TIME_WRITES_TIMER(2);
		stat = f_sync(&kbfile);
		DEBG_WRITER_TIME_WRITES_TIMER(3);

		if (stat != FR_OK)
			current_msg.write_errors++;

		// we're done, return it
		return_write_buffer_idx_after_writing(idx);

		//kbg_setLED2(0);
		// end of flush
		//----------------------------------------------------------------------

#ifdef DEBG_WRITER_TIME_WRITES
		chprintf(DEBG, "%12f, %12f, %12f, %d, %6d, 0x%.8d\n",
				(t1-t0) / 168000.0f, (t3-t2) / 168000.0f, (t3-t0) / 168000.0f,
				idx, bytes_written, buf->buffer);
#endif // DEBG_WRITER_TIME_WRITES

		kbs_setWriteCount(current_msg.msg_num);
		kbs_setWriteErrors(current_msg.write_errors);

		// after X buffers, start a new file. this has to be in sync with
		// the logger thread, so that you both do roll over at the same time
		writer_buffers_written++;
		if ( writer_buffers_written > MAX_BUFFERS_PER_FILE )
		{
			writer_buffers_written = 0;
			// we've hit the file size limit, close the old, open a new file
			if ( new_file() != FR_OK )
			{
				// no new file? that's bad!!
				logger_state = LS_WAIT_FOR_SD;
				break;
			}
		}

		sd_card_status();
		if (LS_RUNNING != logger_state)
			break;

	}
	return ret;
}
Example #22
0
int main(int argc, char *argv[]) {

	QApplication::setApplicationName("photoqt");

	// This string holds the current version
	QString globVersion = QString::fromStdString(VERSION);

	// A help message for the command line
	QString hlp = "\nPhotoQt v" + globVersion + " -  Copyright (C) 2013, Lukas Spies ([email protected]), License: GPLv2 (or later)\n";
	hlp += "PhotoQt is a fast, simple, good looking, yet powerfull and highly configurable image viewer.\n\n";

	hlp += "Usage: photoqt [options|file]\n\n";

	hlp += "Options:\n";
	hlp += "\t--h, --help\t\tThis help message\n\n";

	hlp += ">> Start-up options:\n\n";

	hlp += "\t--start-in-tray\t\tStart PhotoQt hidden to the system tray\n";
	hlp += "\t--no-thumbs\t\tDon't load thumbnails (Navigation through folder is still possible)\n\n";

	hlp += ">> Remote Controlling:\n\n";

	hlp += "\t--open\t\t\tOpens the open file dialog (also shows PhotoQt if hidden)\n";
	hlp += "\t--toggle\t\tToggles PhotoQt - hides PhotoQt if visible, shows if hidden\n";
	hlp += "\t--show\t\t\tShows PhotoQt (does nothing if already shown)\n";
	hlp += "\t--hide\t\t\tHides PhotoQt (does nothing if already hidden)\n\n";

	hlp += ">> Remote controlling w/ filename needed:\n\n";

	hlp += "\t--no-thumbs [filename]\tDon't load thumbnails (Navigation through folder is still possible)\n";
	hlp += "\t--thumbs [filename]\tReversing a '--no-thumbs' (thumbnails are enabled by default)\n\n";

	hlp += ">> Debuging:\n\n";
	hlp += "\t--v, --verbose\t\tEnabling debug messages\n\n";

	hlp += "\n   Enjoy PhotoQt :-)\n\n\n";

	// This file is updated by a running instance of PhotoQt every 500 milliseconds - check
	QFile chk(QDir::homePath() + "/.photoqt/running");
	QString all = "";
	if(chk.open(QIODevice::ReadOnly)) {
		QTextStream in(&chk);
		all = in.readAll();
	}

	QStringList allArgs;
	for(int i = 0; i < argc; ++i)
		allArgs.append(argv[i]);

	if(QFile(QDir::homePath()+"/.photoqt/verbose").exists())
		allArgs.append("--v");

	QStringList knownArgs;
	knownArgs << "--open";
	knownArgs << "--no-thumbs";
	knownArgs << "--thumbs";
	knownArgs << "--toggle";
	knownArgs << "--show";
	knownArgs << "--hide";
	knownArgs << "--start-in-tray";
	knownArgs << "--verbose";
	knownArgs << "--v";

	/****************************************************/
	// DEVELOPMENT ONLY
	knownArgs << "--update" << "--install";
	// DEVELOPMENT ONLY
	/****************************************************/

	// If PhotoQt was started with "--h" or "--help", show help message
	if(allArgs.contains("--help") || allArgs.contains("-help") || allArgs.contains("--h") || allArgs.contains("-h")) {

		std::cout << hlp.toStdString();

		return 0;

	// If an instance of PhotoQt is running, we check for command line arguments
	} else if(QDateTime::currentMSecsSinceEpoch() - all.toLongLong() < qint64(1020)) {

		// We need to initiate it here to, because we check for the applicationFilePath() later-on
		QApplication a(argc, argv);

		std::cout << "Running instance of PhotoQt detected..." << std::endl;

		// This is the content of the file used to communicate with running PhotoQt instance
		QString cont = "";

		// This boolean is set to true if an unknown command is used
		bool err = false;

		for(int i = 1; i < allArgs.length(); ++i) {

			// We ignore the verbose switch when an instance is already running
			if(allArgs.at(i) != "--v" && allArgs.at(i) != "--verbose") {
				if(knownArgs.contains(allArgs.at(i)))
					cont += allArgs.at(i) + "\n";
				else if(allArgs.at(i).startsWith("-")) {
					err = true;
				} else {
					QString filename = allArgs.at(i);
					if(!filename.startsWith("/"))
						filename = QFileInfo(filename).absoluteFilePath();
					if(filename != a.applicationFilePath())
						cont += "-f-" + filename;
				}
			}

		}

		// If PhotoQt is called without any arguments, "show" is used
		if(allArgs.length() == 1 || (allArgs.length() == 2 && allArgs.contains("--v")))
			cont = "--show";

		// If only correct arguments were used
		if(!err) {
			// Write the commands into this file, which is checked regularly by a running instance of PhotoQt
			QFile f(QDir::homePath() + "/.photoqt/cmd");
			f.remove();
			if(f.open(QIODevice::WriteOnly)) {
				QTextStream out(&f);
				out << cont;
				f.close();
			} else
				std::cerr << "ERROR! Couldn't write to file '~/.photoqt/cmd'. Unable to communicate with running process" << std::endl;

		// If an uncorrect argument was used
		} else
			std::cout << hlp.toStdString();


		return 0;

	// If PhotoQt isn't running and no command line argument (besides filename and "--start-in.tray") was used
	} else {

		bool verbose = (allArgs.contains("--v") || allArgs.contains("--verbose") || QFile(QDir::homePath() + "/.photoqt/verbose").exists() || (!QDir(QDir::homePath() + "/.photoqt").exists() && QFile(QDir::homePath() + "/.photo/verbose").exists()));

		bool migrated = false;

		// Ensure that the config folder exists, and move from ~/.photo to ~/.photoqt
		QDir dir(QDir::homePath() + "/.photoqt");
		if(!dir.exists()) {
			QDir dir_old(QDir::homePath() + "/.photo");
			if(dir_old.exists()) {
				if(verbose) std::clog << "Moving ~/.photo to ~/.photoqt" << std::endl;
				dir.mkdir(QDir::homePath() + "/.photoqt");

				QFile file(QDir::homePath() + "/.photo/contextmenu");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/contextmenu");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/fileformats");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/fileformats");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/running");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/running");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/settings");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/settings");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/shortcuts");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/shortcuts");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/thumbnails");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/thumbnails");
					file.remove();
				}

				file.setFileName(QDir::homePath() + "/.photo/verbose");
				if(file.exists()) {
					file.copy(QDir::homePath() + "/.photoqt/verbose");
					file.remove();
				}

				dir_old.rmdir(dir_old.absolutePath());

				migrated = true;


			} else {
				if(verbose) std::clog << "Creating ~/.photoqt/" << std::endl;
				dir.mkdir(QDir::homePath() + "/.photoqt");
			}
		}

		bool err = false;

		for(int i = 0; i < allArgs.length(); ++i) {
			if(allArgs.at(i).startsWith("-") && !knownArgs.contains(allArgs.at(i)))
				err = true;
		}

		if(err == true) {

			std::cout << hlp.toStdString();

			// Nothing after this return will be executed (PhotoQt will simply quit)
			return 0;
		}

		// This int holds 1 if PhotoQt was updated and 2 if it's newly installed
		int update = 0;
		QString settingsFileTxt = "";

		// Check if the settings file exists. If not, create a file with default settings (i.e. empty file, settings and defaults are handled by globalsettings.h)
		QFile file(QDir::homePath() + "/.photoqt/settings");
		if(!file.exists()) {
			if(!file.open(QIODevice::WriteOnly))
				std::cerr << "ERROR: Couldn't write settings file! Please ensure that you have read&write access to home directory" << std::endl;
			else {
				if(verbose) std::clog << "Creating basic settings file" << std::endl;
				QTextStream out(&file);
				out << "Version=" + globVersion + "\n";
				file.close();
			}

			update = 2;

		// If file does exist, check if it is from a previous version -> PhotoQt was updated
		} else {
			if(!file.open(QIODevice::ReadWrite))
				std::cerr << "ERROR: Couldn't read settings file! Please ensure that you have read&write access to home directory" << std::endl;
			else {
				QTextStream in(&file);
				settingsFileTxt = in.readAll();

				if(verbose) std::clog << "Checking if first run of new version" << std::endl;

				// If it doesn't contain current version (some previous version)
				if(!settingsFileTxt.contains("Version=" + globVersion + "\n")) {
					file.close();
					file.remove();
					file.open(QIODevice::ReadWrite);
					QStringList allSplit = settingsFileTxt.split("\n");
					allSplit.removeFirst();
					QString allFile = "Version=" + globVersion + "\n" + allSplit.join("\n");
					in << allFile;
					update = 1;
				}

				file.close();

			}
		}

		/****************************************************/
		// DEVELOPMENT ONLY
		if(allArgs.contains("--update")) update = 1;
		if(allArgs.contains("--install")) update = 2;
		// DEVELOPMENT ONLY
		/****************************************************/

#ifdef GM
		Magick::InitializeMagick(*argv);
#endif

		if(QFile(QDir::homePath()+"/.photoqt/cmd").exists())
			QFile(QDir::homePath()+"/.photoqt/cmd").remove();

		// This boolean stores if PhotoQt needs to be minimized to the tray
		bool startintray = allArgs.contains("--start-in-tray");

		// If PhotoQt is supposed to be started minimized in system tray
		if(startintray) {
			if(verbose) std::clog << "Starting minimised to tray" << std::endl;
			// If the option "Use Tray Icon" in the settings is not set, we set it
			QFile set(QDir::homePath() + "/.photoqt/settings");
			if(set.open(QIODevice::ReadOnly)) {
				QTextStream in(&set);
				QString all = in.readAll();
				if(!all.contains("TrayIcon=1")) {
					if(all.contains("TrayIcon=0"))
						all.replace("TrayIcon=0","TrayIcon=1");
					else
						all += "\n[Temporary Appended]\nTrayIcon=1\n";
					set.close();
					set.remove();
					if(!set.open(QIODevice::WriteOnly))
						std::cerr << "ERROR: Can't enable tray icon setting!" << std::endl;
					QTextStream out(&set);
					out << all;
					set.close();
				} else
					set.close();
			} else
				std::cerr << "Unable to ensure TrayIcon is enabled - make sure it is enabled!!" << std::endl;
		}

		QApplication a(argc, argv);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
		// Opt-in to High DPI usage of Pixmaps for larger screens with larger font DPI
		a.setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#endif

		// LOAD THE TRANSLATOR
		QTranslator trans;

		// We use two strings, since the system locale usually is of the form e.g. "de_DE"
		// and some translations only come with the first part, i.e. "de",
		// and some with the full string. We need to be able to find both!
		if(verbose) std::clog << "Checking for translation" << std::endl;
		QString code1 = "";
		QString code2 = "";
		if(settingsFileTxt.contains("Language=") && !settingsFileTxt.contains("Language=en") && !settingsFileTxt.contains("Language=\n")) {
			code1 = settingsFileTxt.split("Language=").at(1).split("\n").at(0).trimmed();
			code2 = code1;
		} else if(!settingsFileTxt.contains("Language=en")) {
			code1 = QLocale::system().name();
			code2 = QLocale::system().name().split("_").at(0);
		}
		if(verbose) std::clog << "Found following language: " << code1.toStdString()  << "/" << code2.toStdString() << std::endl;
		if(QFile(":/lang/photoqt_" + code1 + ".qm").exists()) {
			std::clog << "Loading Translation:" << code1.toStdString() << std::endl;
			trans.load(":/lang/photoqt_" + code1);
			a.installTranslator(&trans);
			code2 = code1;
		} else if(QFile(":/lang/photoqt_" + code2 + ".qm").exists()) {
			std::clog << "Loading Translation:" << code2.toStdString() << std::endl;
			trans.load(":/lang/photoqt_" + code2);
			a.installTranslator(&trans);
			code1 = code2;
		}

		// Check if thumbnail database exists. If not, create it
		QFile database(QDir::homePath() + "/.photoqt/thumbnails");
		if(!database.exists()) {

			if(verbose) std::clog << "Create Thumbnail Database" << std::endl;

			QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "thumbDB");
			db.setDatabaseName(QDir::homePath() + "/.photoqt/thumbnails");
			if(!db.open()) std::cerr << "ERROR: Couldn't open thumbnail database:" << db.lastError().text().trimmed().toStdString() << std::endl;
			QSqlQuery query(db);
			query.prepare("CREATE TABLE Thumbnails (filepath TEXT,thumbnail BLOB, filelastmod INT, thumbcreated INT, origwidth INT, origheight INT)");
			query.exec();
			if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Creating Thumbnail Datbase):" << query.lastError().text().trimmed().toStdString() << std::endl;
			query.clear();


		} else {

			if(verbose) std::clog << "Opening Thumbnail Database" << std::endl;

			// Opening the thumbnail database
			QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","thumbDB");
			db.setDatabaseName(QDir::homePath() + "/.photoqt/thumbnails");
			if(!db.open()) std::cerr << "ERROR: Couldn't open thumbnail database:" << db.lastError().text().trimmed().toStdString() << std::endl;

			if(migrated) {
				QSqlQuery query(db);
				query.prepare("ALTER TABLE Thumbnails ADD COLUMN origwidth INT");
				query.exec();
				if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Adding origwidth to Thumbnail Database):" << query.lastError().text().trimmed().toStdString() << std::endl;
				query.clear();
				query.prepare("ALTER TABLE Thumbnails ADD COLUMN origheight INT");
				query.exec();
				if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Adding origheight to Thumbnail Database):" << query.lastError().text().trimmed().toStdString() << std::endl;
				query.clear();
			}

		}


		// Previous versions of PhotoQt checked here also for the shortcuts file. We don't need to do that anymore, since all shortcuts including the defaults are handled by shortcuts.h


		/***************************
		 ***************************/
		// The Window has to be initialised *AFTER* the checks above to ensure that the settings exist and are updated and can be loaded
		MainWindow w(0,verbose);
		/***************************
		 ***************************/

		// We move from old way of handling image formats to new way
		// We can't do it before here, since we need access to global settings
		QFile old_qt(QDir::homePath() + "/.photoqt/fileformatsQt");
		QFile old_gm(QDir::homePath() + "/.photoqt/fileformatsGm");
		QFile new_file(QDir::homePath() + "/.photoqt/fileformats.disabled");
		if((old_qt.exists() || old_gm.exists()) && !new_file.exists()) {

			// These will be the sets of known file formats
			QStringList new_qt;
			QStringList new_gm;

			// Read in formats supported by qt
			if(old_qt.exists()) {
				if(!old_qt.open(QIODevice::ReadOnly))
					std::cerr << "[migrate fileformats] ERROR: Can't open old file with qt file formats";
				else {
					QTextStream in(&old_qt);
					QString line = in.readLine();
					while (!line.isNull()) {
						if(line.trimmed().length() != 0) new_qt << "*" + line.trimmed();
						line = in.readLine();
					}
					old_qt.close();
				}
				// Remove old and redundant file
				if(!old_qt.remove())
					std::cerr << "[migrate fileformats] WARNING: Can't remove old (redundant) file with qt file formats";
			}

			// Read in formats supported by gm
			if(old_gm.exists()) {
				if(!old_gm.open(QIODevice::ReadOnly))
					std::cerr << "[migrate fileformats] ERROR: Can't open old file with gm file formats";
				else {
					QTextStream in(&old_gm);
					QString line = in.readLine();
					while (!line.isNull()) {
						if(line.trimmed().length() != 0) new_gm << "*" + line.trimmed();
						line = in.readLine();
					}
					old_gm.close();
				}
				// Remove old and redundant file
				if(!old_gm.remove())
					std::cerr << "[migrate fileformats] WARNING: Can't remove old (redundant) file with gm file formats";
			}

			// File content of disabled fileformats
			QString fileformatsDisabled = "";

			// New fileformats that were not part of previous versions of PhotoQt
			QStringList newfileformats;
			newfileformats << "*.cin";
			newfileformats << "*.mono";
			newfileformats << "*.sfw";
			newfileformats << "*.txt";
			newfileformats << "*.wpg";

			// QT: If not supported, it is disabled
			QStringList qtDef;
			qtDef << "*.bmp, *.bitmap"
				<< "*.dds"
				<< "*.gif"
				<< "*.ico, *.icns"
				<< "*.jpg, *.jpeg"
				<< "*.jpeg2000, *.jp2, *.jpc, *.j2k, *.jpf, *.jpx, *.jpm, *.mj2"
				<< "*.mng"
				<< "*.png"
				<< "*.pbm"
				<< "*.pgm"
				<< "*.ppm"
				<< "*.svg, *.svgz"
				<< "*.tif, *.tiff"
				<< "*.wbmp, *.webp"
				<< "*.xbm"
				<< "*.xpm";
			QList<QByteArray> qtSup = QImageReader::supportedImageFormats();
			foreach(QString q, qtDef) {
				QStringList parts = q.split(", ");
				bool disabled = true;
				foreach(QString p, parts) {
					if(qtSup.contains(p.remove(0,2).toLower().trimmed().toLatin1())) {
						disabled = false;
						break;
					}
				}
				if(disabled)
					fileformatsDisabled += parts.join("\n") + "\n";
			}

			// GM: If not enabled, it is disabled - new fileformats are ENabled by default
			QStringList gmDef = w.globSet->fileFormats->formatsGmEnabled;
			foreach(QString g, gmDef) {
				if(!new_gm.contains(g) && !newfileformats.contains(g))
					fileformatsDisabled += g + "\n";
			}

			// Extras are disabled by default
			fileformatsDisabled += "**.xcf\n**.psd\n**.psb\n";

			// Untested are disabled by default
			if(!fileformatsDisabled.contains("*.hp\n")) fileformatsDisabled += "*.hp\n";
			if(!fileformatsDisabled.contains("*.hpgl\n")) fileformatsDisabled += "*.hpgl\n";
			if(!fileformatsDisabled.contains("*.jbig\n")) fileformatsDisabled += "*.jbig\n";
			if(!fileformatsDisabled.contains("*.jbg\n")) fileformatsDisabled += "*.jbg\n";
			if(!fileformatsDisabled.contains("*.pwp\n")) fileformatsDisabled += "*.pwp\n";
			if(!fileformatsDisabled.contains("*.rast\n")) fileformatsDisabled += "*.rast\n";
			if(!fileformatsDisabled.contains("*.rla\n")) fileformatsDisabled += "*.rla\n";
			if(!fileformatsDisabled.contains("*.rle\n")) fileformatsDisabled += "*.rle\n";
			if(!fileformatsDisabled.contains("*.sct\n")) fileformatsDisabled += "*.sct\n";
			if(!fileformatsDisabled.contains("*.tim\n")) fileformatsDisabled += "*.tim\n";

			// Write 'disabled filetypes' file
			if(new_file.open(QIODevice::WriteOnly)) {
				QTextStream out(&new_file);
				out << fileformatsDisabled;
				new_file.close();
			} else
				std::cerr << "ERROR: Can't write default disabled fileformats file" << std::endl;


			// Update settings with new values
			w.globSet->fileFormats->getFormats();

		}
Example #23
0
int main(void)
{
//extern variables
char *help_topic=NULL,*fname=NULL,buff[5000]={'\0'},file[50]={};
int logc,logr,ch,i,j,k,flag;
FILE *fp;

// initialise curses mode and colors
initCurses();
noecho();
cbreak();
keypad(stdscr,TRUE);
mousemask(ALL_MOUSE_EVENTS,NULL);
curs_set(0);

//displays starting blue screen
Screen();
	while(1)
	{
		int ch;
		ch=getResponse();
		switch(ch)
		{
			//file menu
			case 1:
					//pop up menu file
					(WINDOW**)draw_menu(fmenu,SIZE(fmenu),1,0);
			break;
			
			//new item
			case 2:
				refresh();
				//draws black screen
				new_file();
				noecho();
				//displays filename and line number on black screen
				New();						
			break;
			
			//Return To Shell
			case 5:
				clear();
	       		refresh();
	       		endwin();
	       		system("sh");
	       		clear();
				refresh();
				Screen();
			break;
			
			//exit menu
			case 6:
				clear();
	    		refresh();
				endwin();
				exit(EXIT_SUCCESS);
			break;
			
			/*compile menu
			case 7:
				//pop up menu compile
					(WINDOW**)draw_menu(cmenu,SIZE(cmenu),1,12);
			break;
			
			*/
			/*compile item
			case 8:
				compile();
			break;*/
			
			//help menu
			case 11:
				//pop up  help menu
 					(WINDOW**)draw_menu(hmenu,SIZE(hmenu),1,27);
			break;
			
			//help index
			case KEY_F(1):
			case 12:
				Help();
			break;
			
			//help topic
			case 13:
				help_topic=(char*)calloc(30,sizeof(char));
				help_topic=dialog("| Help |"," Find "," Cancel ");
			break;
			
			
			
			//open file
			case KEY_F(3):
			case 3:
						k=0;
					for(i=2;i<22;++i)
					{
						for(j=0;j<78;++j)
							buff[k++]=(mvinch(i,j)&A_CHARTEXT);
						buff[k++]='\n';
					}
				new_file();
					//pops up open dialogbox				
				fname=(char*)calloc(30,sizeof(char));
				fname=dialog("| Open |"," Open "," Cancel ");
				
				//if user press cancel display screen contents
				if((strlen(fname)==0))
				{
					logc=1;logr=2;
					for(k=0;buff[k]!='\0';++k)
					{
						refresh();
						if(buff[k]=='\n')
						{
					        logr+=1;
					        logc=1;
					       	move(logr+1,logc);
						}
						else
						{
							mvaddch(logr,logc,buff[k]);
							logc+=1;
						}
					}
				}
				
				//othewise open a file and display it's contents
				else
				{
					//redraws new screen
					new_file();
				
				
					if(!(fp=fopen(fname,"r")))
					{
						warning("| Warning |","	No such file ","Press a key to return !!!");
						getch();
						//new_file();
							logc=1;logr=2;
							for(k=0;buff[k]!='\0';++k)
							{
								refresh();
								if(buff[k]=='\n')
								{
					        		logr+=1;
					        		logc=1;
					       			 move(logr+1,logc);
								}
								else
								{
									mvaddch(logr,logc,buff[k]);
									logc+=1;
								}
							}	
					
					}
					//if file is exist display contents 
					else
					{	
						new_file();
						logc=1;logr=2;
						while((ch=fgetc(fp))!=EOF)
						{
							if(ch=='\n')
							{
						        logr+=1;
						        logc=1;
						        move(logr+1,logc);
							}
							else
							{
								mvaddch(logr,logc,ch);
								logc+=1;
							}
						}
						fclose(fp);
						move(2,2);
						refresh();
						
						//displays file name
							move(1,2);
						hline(ACS_HLINE,75);
						strcat(file,"| ");
						strcat(file,fname);
						strcat(file," |");
						//move(1,2);
						//hline(ACS_HLINE,60);
						writeString(stdscr,1,35,file,white_black);
					}
				}
			break;
			
			
		}
	}
}