// Метод должен возвращать уровень сложности сделанных изменений
// 0 - изменения не требуют перезапуска программы
// 1 - изменения требуют перезапуска программы
int AppConfigPage_Misc::apply_changes(void)
{
 qDebug() << "Apply changes misc";
 
 // Сохраняется настройка подтверждения для действия "cut" на ветке
 if(mytetraconfig.get_cutbranchconfirm()!=cutBranchConfirm->isChecked())
  mytetraconfig.set_cutbranchconfirm(cutBranchConfirm->isChecked());

 // Сохраняется настройка отображения отладочных сообщений в консоли
 if(mytetraconfig.get_printdebugmessages()!=printDebugMessages->isChecked())
  mytetraconfig.set_printdebugmessages(printDebugMessages->isChecked());

 // Сохраняется настройка режима запуска MyTetra - обычный или свернутый
 if(mytetraconfig.get_runinminimizedwindow()!=runInMinimizedWindow->isChecked())
  mytetraconfig.set_runinminimizedwindow(runInMinimizedWindow->isChecked());

 // Сохраняется настройка нужно ли вспоминать позицию курсора при перемещении
 // по истории
 if(mytetraconfig.getRememberCursorAtHistoryNavigation()!=rememberAtHistoryNavigationCheckBox->isChecked())
  mytetraconfig.setRememberCursorAtHistoryNavigation(rememberAtHistoryNavigationCheckBox->isChecked());
 
 // Сохраняется настройка нужно ли пытаться вспоминать позицию курсора при
 // обычном выборе записи
 if(mytetraconfig.getRememberCursorAtOrdinarySelection()!=rememberAtOrdinarySelectionCheckBox->isChecked())
  mytetraconfig.setRememberCursorAtOrdinarySelection(rememberAtOrdinarySelectionCheckBox->isChecked());

 return 0;
}
示例#2
0
	void UIModule::Start()
	{
		SharedKMethod api = this->host->GetGlobalObject()->GetNS("API.fire")->ToMethod();
		api->Call("ti.UI.start", Value::Undefined);

#ifdef OS_WIN32
		UIBinding* binding = new Win32UIBinding(host);
#elif OS_OSX
		UIBinding* binding = new OSXUIBinding(host);
#elif OS_LINUX
		UIBinding* binding = new GtkUIBinding(host);
#endif

		AppConfig *config = AppConfig::Instance();
		if (config == NULL)
		{
			std::string msg = "Error loading tiapp.xml. Your application "
			                  "is not properly configured or packaged.";
			binding->ErrorDialog(msg);
			throw ValueException::FromString(msg.c_str());
			return;
		}
		WindowConfig *main_window_config = config->GetMainWindow();
		if (main_window_config == NULL)
		{
			std::string msg ="Error loading tiapp.xml. Your application "
			                 "window is not properly configured or packaged.";
			binding->ErrorDialog(msg);
			throw ValueException::FromString(msg.c_str());
			return;
		}

		binding->CreateMainWindow(main_window_config);
	}
void FindTableWidget::setupUI(void)
{
    findTableView=new QTableView(this);
    findTableView->setObjectName("findTableView");
    findTableView->setMinimumSize(1,1);
    findTableView->horizontalHeader()->hide();

// Установка высоты строки с принудительной стилизацией (если это необходимо),
// так как стилизация через QSS для элементов QTableView полноценно не работает
// У таблицы есть вертикальные заголовки, для каждой строки, в которых отображается номер строки.
// При задании высоты вертикального заголовка, высота применяется и для всех ячеек в строке.
    findTableView->verticalHeader()->setDefaultSectionSize ( findTableView->verticalHeader()->minimumSectionSize () );
    int height=mytetraConfig.getUglyQssReplaceHeightForTableView();
    if(height!=0)
        findTableView->verticalHeader()->setDefaultSectionSize( height );
    if(mytetraConfig.getInterfaceMode()=="mobile")
        findTableView->verticalHeader()->setDefaultSectionSize( getCalculateIconSizePx() );

// Устанавливается режим что могут выделяться только строки
// а не отдельный item таблицы
    findTableView->setSelectionBehavior(QAbstractItemView::SelectRows);

// Устанавливается режим что редактирование невозможно
    findTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

// Настройка области виджета для кинетической прокрутки
    setKineticScrollArea( qobject_cast<QAbstractItemView*>(findTableView) );
}
void TreeScreen::setupSignals(void)
{
// Соединение сигнал-слот чтобы показать контекстное меню по правому клику на ветке
    connect(knowTreeView, SIGNAL(customContextMenuRequested(const QPoint &)),
            this,SLOT(on_customContextMenuRequested(const QPoint &)));

// Соединение сигнал-слот чтобы показать контекстное меню по долгому нажатию
    connect(knowTreeView, SIGNAL(tapAndHoldGestureFinished(const QPoint &)),
            this, SLOT(on_customContextMenuRequested(const QPoint &)));

// Соединение сигнал-слот что ветка выбрана мышкой или стрелками на клавиатуре
    if(mytetraConfig.getInterfaceMode()=="desktop")
        connect(knowTreeView->selectionModel(), SIGNAL(currentRowChanged (const QModelIndex&, const QModelIndex&)),
                this, SLOT(on_knowtree_clicked(const QModelIndex&)));

    if(mytetraConfig.getInterfaceMode()=="mobile")
        connect(knowTreeView, SIGNAL(clicked(const QModelIndex &)),
                this, SLOT(on_knowtree_clicked(const QModelIndex &)));

// Сигнал чтобы открыть на редактирование параметры записи при двойном клике
// connect(knowTreeView, SIGNAL(doubleClicked(const QModelIndex &)),
//         actionList["editBranch"], SLOT(trigger(void)));

// Сигнал что ветка выбрана мышкой
// connect(knowTreeView,SIGNAL(pressed(const QModelIndex &)),
//         this,SLOT(on_knowTreeView_clicked(const QModelIndex &)));
// connect(knowTreeView, SIGNAL(clicked(const QModelIndex &)),
//         this, SLOT(on_knowTreeView_clicked(const QModelIndex &)));

}
示例#5
0
void CommandWidget::onCheckBoxShowAdvancedStateChanged(int state)
{
    const bool showAdvanced = state == Qt::Checked;
    AppConfig appConfig;
    appConfig.setOption(Config::show_advanced_command_settings::name(), showAdvanced);
    ui->tabWidget->setVisible(showAdvanced);
    ui->labelDescription->setVisible(showAdvanced);
}
示例#6
0
					void Client::main(std::string args[])
					{
						//创建读取应用配置的对象
						AppConfig *config = new AppConfig();

						std::string paramA = config->getParameterA();
						std::string paramB = config->getParameterB();

						puts("paramA="+paramA+",paramB="+paramB);
					}
示例#7
0
void SDRDevicesDialog::OnUseSelected( wxMouseEvent& event ) {
    if (dev != NULL) {
        int i = 0;
        SoapySDR::ArgInfoList::const_iterator args_i;
        SoapySDR::ArgInfoList args = dev->getSettingsArgInfo();
        
        SoapySDR::Kwargs settingArgs;
        SoapySDR::Kwargs streamArgs;
        
        for (args_i = args.begin(); args_i != args.end(); args_i++) {
            SoapySDR::ArgInfo arg = (*args_i);
            wxPGProperty *prop = props[i];
            
            if (arg.type == SoapySDR::ArgInfo::STRING && arg.options.size()) {
                settingArgs[arg.key] = arg.options[prop->GetChoiceSelection()];
            } else if (arg.type == SoapySDR::ArgInfo::BOOL) {
                settingArgs[arg.key] = (prop->GetValueAsString()=="True")?"true":"false";
            } else {
                settingArgs[arg.key] = prop->GetValueAsString();
            }
            
            i++;
        }
        
        if (dev->getRxChannel()) {
            args = dev->getRxChannel()->getStreamArgsInfo();
            
            if (args.size()) {
                for (args_i = args.begin(); args_i != args.end(); args_i++) {
                    SoapySDR::ArgInfo arg = (*args_i);
                    wxPGProperty *prop = props[i];
            
                    if (arg.type == SoapySDR::ArgInfo::STRING && arg.options.size()) {
                        streamArgs[arg.key] = arg.options[prop->GetChoiceSelection()];
                    } else if (arg.type == SoapySDR::ArgInfo::BOOL) {
                        streamArgs[arg.key] = (prop->GetValueAsString()=="True")?"true":"false";
                    } else {
                        streamArgs[arg.key] = prop->GetValueAsString();
                    }
                    
                    i++;
                }
            }
        }
        
        AppConfig *cfg = wxGetApp().getConfig();
        DeviceConfig *devConfig = cfg->getDevice(dev->getDeviceId());
        devConfig->setSettings(settingArgs);
        devConfig->setStreamOpts(streamArgs);
        wxGetApp().setDeviceArgs(settingArgs);
        wxGetApp().setStreamArgs(streamArgs);
        wxGetApp().setDevice(dev);
        Close();
    }
}
void TreeScreen::setupUI(void)
{
    toolsLine=new QToolBar(this);

    /*
    QSize tool_bar_icon_size(16,16);
    toolsLine->setIconSize(tool_bar_icon_size);
    */

    insertActionAsButton(toolsLine, actionList["insSubbranch"]);
    insertActionAsButton(toolsLine, actionList["insBranch"]);

    if(mytetraConfig.getInterfaceMode()=="desktop") {
        insertActionAsButton(toolsLine, actionList["editBranch"]);
        insertActionAsButton(toolsLine, actionList["delBranch"]);
    }

    toolsLine->addSeparator();

    insertActionAsButton(toolsLine, actionList["expandAllSubbranch"]);
    insertActionAsButton(toolsLine, actionList["collapseAllSubbranch"]);

    toolsLine->addSeparator();

    insertActionAsButton(toolsLine, actionList["moveUpBranch"]);
    insertActionAsButton(toolsLine, actionList["moveDnBranch"]);

    if(mytetraConfig.getInterfaceMode()=="mobile") {
        toolsLine->addSeparator();
        insertActionAsButton(toolsLine, actionList["findInBase"]); // Клик по этой кнопке связывается с действием в MainWindow
    }


    knowTreeView=new KnowTreeView(this);
    knowTreeView->setObjectName("knowTreeView");
    knowTreeView->setMinimumSize(150,250);
    knowTreeView->setWordWrap(true);

// Временно сделан одинарный режим выбора пунктов
// todo: Множественный режим надо выставить тогда, когда
// станет ясно, как удалять несколько произвольных веток так, чтобы
// в процессе удаления QModelIndex нижестоящих еще не удаленных
// веток не менялся
// knowTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    knowTreeView->setSelectionMode(QAbstractItemView::SingleSelection);

    knowTreeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

// Нужно установить правила показа контекстного самодельного меню
// чтобы оно могло вызываться
    knowTreeView->setContextMenuPolicy(Qt::CustomContextMenu);

// Представление не должно позволять редактировать элементы обычным путем
    knowTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
示例#9
0
文件: main.cpp 项目: karlp/mqblynk
static
void parse_options(int argc, char* argv[], AppConfig &conf)
{
	static struct option long_options[] = {
		{"help", no_argument, 0, 'h'},
		{"config", required_argument, 0, 'c'},
		{0, 0, 0, 0}
	};
	
	// Set default values TODO - make a member function?
	conf.blynk_server = BLYNK_DEFAULT_DOMAIN;
	conf.blynk_port = TOSTRING(BLYNK_DEFAULT_PORT);
	conf.mqtt_port = 1883;
	conf.mqtt_server = MQTT_DEFAULT_DOMAIN;
	
	const char* usage =
		"Usage: %s [options]\n"
		"\n"
		"Options:\n"
		"  -h, --help  Print this help\n"
		"  -c config.json, --config=configfile.json JSON Configuration file.\n"
		"\n"
		"Defaults:\n"
		"  Unless specified in the config file, the following defaults are used:"
		"  blynk.server: " BLYNK_DEFAULT_DOMAIN "\n"
		"  blynk.port" TOSTRING(BLYNK_DEFAULT_PORT) "\n"
		"  mqtt.server: " MQTT_DEFAULT_DOMAIN "\n"
		"  outputs: empty list"
		"\n";

	int rez;
	while (-1 != (rez = getopt_long(argc, argv, "hc:", long_options, NULL))) {
		switch (rez) {
		case 'c':
			if (conf.parse(optarg)) {
				printf("Config successfully loaded from: %s\n", optarg);
			} else {
				printf("Failed to parse config from: %s: %s\n", optarg, conf.failure());
			}
			break;
		case 'h':
		default:
			printf(usage, argv[0]);
			exit(0);
		};
	};
	// Allowed to load extra settings here.

	// Check mandatory options
	if (!conf.is_valid()) {
		printf("Final configuraton is invalid: %s\n", conf.failure());
		exit(1);
	}
	conf.dump();
}
示例#10
0
//Behavior when unchecking 'Presets' is to keep the GUI settings at the last preset (even if not yet applied).
//
//Alternative possible behavior when unchecking 'Presets' (currently not implemented) is to set the GUI to
//	the last applied settings. If such behavior is to be implemented, g_Conf->EnablePresets should be set to
//	false before it's applied to the GUI and then restored to it's original state such that the GUI reflects
//	g_Conf's settings as if it doesn't force presets. (if a settings which has presets enable is applied to the
//	GUI then most of the GUI is disabled).
void Dialogs::SysConfigDialog::UpdateGuiForPreset ( int presetIndex, bool presetsEnabled )
{
 	if( !m_listbook )
		return;

	//Console.WriteLn("Applying config to Gui: preset #%d, presets enabled: %s", presetIndex, presetsEnabled?"true":"false");

	AppConfig preset = *g_Conf;
	preset.IsOkApplyPreset( presetIndex );	//apply a preset to a copy of g_Conf.
	preset.EnablePresets = presetsEnabled;	//override IsOkApplyPreset (which always applies/enabled) to actual required state
	
	//update the config panels of SysConfigDialog to reflect the preset.
	size_t pages = m_labels.GetCount();
	for( size_t i=0; i<pages; ++i )
	{
		//NOTE: We should only apply the preset to panels of class BaseApplicableConfigPanel_SpecificConfig
		//      which supports it, and BaseApplicableConfigPanel implements IsSpecificConfig() as lame RTTI to detect it.
		//		However, the panels in general (m_listbook->GetPage(i)) are of type wxNotebookPage which doesn't
		//		support IsSpecificConfig(), so the panels (pages) that SysConfigDialog holds must be of class
		//		BaseApplicableConfigPanel or derived, and not of the parent class wxNotebookPage.
		if ( ((BaseApplicableConfigPanel*)(m_listbook->GetPage(i)))->IsSpecificConfig() )
		{
			((BaseApplicableConfigPanel_SpecificConfig*)(m_listbook->GetPage(i)))
				->ApplyConfigToGui( preset, AppConfig::APPLY_FLAG_FROM_PRESET | AppConfig::APPLY_FLAG_MANUALLY_PROPAGATE );
		}
	}

	//Main menus behavior regarding presets and changes/cancel/apply from SysConfigDialog:
	//1. As long as preset-related values were not changed at SysConfigDialog, menus behave normally.
	//2. After the first preset-related change at SysConfigDialog (this function) and before Apply/Ok/Cancel:
	//	- The menus reflect the temporary pending values, but these preset-controlled items are grayed out even if temporarily presets is unchecked.
	//3. When clicking Ok/Apply/Cancel at SysConfigDialog, the menus are re-alligned with g_Conf (including gray out or not as needed).
	//NOTE: Enabling the presets and disabling them wihout clicking Apply leaves the pending menu config at last preset values
	//		(consistent with SysConfigDialog behavior). But unlike SysConfigDialog, the menu items stay grayed out.
	//		Clicking cancel will revert all pending changes, but clicking apply will commit them, and this includes the menus.
	//		E.g.:
	//			1. Patches (menu) is disabled and presets (SysConfigDialog) is disabled.
	//			2. Opening config and checking presets without apply --> patches are visually enabled and grayed out (not yet applied to g_Conf)
	//			3. Unchecking presets, still without clicking apply  --> patches are visually still enabled (last preset values) and grayed out.
	//			4. Clicking Apply (presets still unchecked) --> patches will be enabled and not grayed out, presets are disabled.
	//			--> If clicking Cancel instead of Apply at 4., will revert everything to the state of 1 (preset disabled, patches disabled and not grayed out).
	
	bool origEnable=preset.EnablePresets;
	preset.EnablePresets=true;	// will cause preset-related items to be grayed out at the menus regardless of their value.
	if ( GetMainFramePtr() )
		GetMainFramePtr()->ApplyConfigToGui( preset, AppConfig::APPLY_FLAG_FROM_PRESET | AppConfig::APPLY_FLAG_MANUALLY_PROPAGATE );
	
	// Not really needed as 'preset' is local and dumped anyway. For the sake of future modifications of more GUI elements.
	preset.EnablePresets=origEnable;	
	
}
示例#11
0
AppConfigPage_Misc::AppConfigPage_Misc(QWidget *parent) : ConfigPage(parent)
{
  qDebug() << "Create misc config page";

  // Блок настройки подтверждения для действия "cut" на ветке
  cutBranchConfirm=new QCheckBox(this);
  cutBranchConfirm->setText(tr("Confirm item cut"));
  cutBranchConfirm->setChecked(mytetraconfig.get_cutbranchconfirm());

  // Блок настройки отображения отладочных сообщений в консоли
  printDebugMessages=new QCheckBox(this);
  printDebugMessages->setText(tr("Print debug messages to console"));
  printDebugMessages->setChecked(mytetraconfig.get_printdebugmessages());

  // Настройка запуска MyTetra в свернутом окне
  runInMinimizedWindow=new QCheckBox(this);
  runInMinimizedWindow->setText(tr("Run MyTetra in a minimized window"));
  runInMinimizedWindow->setChecked(mytetraconfig.get_runinminimizedwindow());


  // Группировщик виджетов для настройки автоматического старта синхронизации
  historyBox=new QGroupBox(this);
  historyBox->setTitle(tr("History of visited notes"));

  rememberAtHistoryNavigationCheckBox=new QCheckBox(this);
  rememberAtHistoryNavigationCheckBox->setText(tr("Remember cursor position at history navigation"));
  rememberAtHistoryNavigationCheckBox->setChecked(mytetraconfig.getRememberCursorAtHistoryNavigation());

  rememberAtOrdinarySelectionCheckBox=new QCheckBox(this);
  rememberAtOrdinarySelectionCheckBox->setText(tr("Try remember cursor position at ordinary selection"));
  rememberAtOrdinarySelectionCheckBox->setChecked(mytetraconfig.getRememberCursorAtOrdinarySelection());

  // Виджеты вставляются в группировщик
  QVBoxLayout *historyLayout = new QVBoxLayout;
  historyLayout->addWidget(rememberAtHistoryNavigationCheckBox);
  historyLayout->addWidget(rememberAtOrdinarySelectionCheckBox);
  historyBox->setLayout(historyLayout);


  // Собирается основной слой
  QVBoxLayout *central_layout=new QVBoxLayout();
  central_layout->addWidget(cutBranchConfirm);
  central_layout->addWidget(printDebugMessages);
  central_layout->addWidget(runInMinimizedWindow);
  central_layout->addWidget(historyBox);
  central_layout->addStretch();

  // Основной слой устанавливается
  setLayout(central_layout);
}
示例#12
0
void ConsoleEmulator::onDetailsClick(void)
{
 if(consoleOutput->isHidden())
  {
   consoleOutput->show();
   mytetraconfig.setSyncroConsoleDetails(true);
  }
 else
  {
   consoleOutput->hide();
   mytetraconfig.setSyncroConsoleDetails(false);
  }

 this->adjustSize();
}
示例#13
0
文件: LogList.cpp 项目: tkas/gcm
GC<Log> LogList::append(GC<Log> log) {
	// Append to set
	List<Log>::append(log);
	
	// Try to match user name of log
	if (log->getCache() && !log->getCache()->isFound()) {
		AppConfig *cfg = AppConfig::getInstance();
		const char *nick;
		if ((nick = cfg->getString("username", NULL)) != NULL) {
			if ((log->getType() == Log::T_FOUND_IT || log->getType() == Log::T_ATTENDED || log->getType() == Log::T_WEBCAM_PHOTO_TAKEN) && log->getFinder()->equals(nick)) {
				int logtm = 0;
			
				// Try to find time in log 
				const char *text = log->getText()->c_str();
				size_t len = log->getText()->length();
				for (size_t i = 0; i < len; i++) {
					if (text[i] == ':' && i >= 1 && i < len - 1) {
						// Try to find forward and backward numbers.
						
						// Forward first
						if (isdigit(text[i+1]) && (i == len - 2 || isdigit(text[i+2]))) {
							int min = atoi(text + i + 1);
							if (min >= 0 && min <= 59) {
								// Found forward correct minute, search backwards.
								size_t t = i - 1;
								while (t > 0 && isdigit(text[t])) {
									t--;
								}
								
								int hour = atoi(text + t);
								
								if (hour >= 0 && hour <= 23) {
									// Found correct time, set it and stop searching.
									logtm = hour * 3600 + min * 60;
 									break;
								}
							}
						}
					}
				}
		
				log->getCache()->setDtFound(log->getTime() + logtm);
			}
		}
	}
	
	return log;
}
示例#14
0
void AppConfigPage_Misc::onClickedEditMyTetraConfigFile(void)
{
  // Сбрасываются в файл конфига все возможные изменения, которые, возможно еще не были записаны
  mytetraConfig.sync();

  editConfigFile( globalParameters.getWorkDirectory()+"/conf.ini", 0.8 );
}
示例#15
0
void RecordTableScreen::setupUI(void)
{
 toolsLine=new QToolBar(this);

 /*
 QSize toolBarIconSize(16,16);
 toolsLine->setIconSize(toolBarIconSize);
 */

 if(mytetraConfig.getInterfaceMode()=="mobile")
 {
   insertActionAsButton(toolsLine, actionBack);
   toolsLine->addSeparator();
 }

 insertActionAsButton(toolsLine, actionAddNewToEnd);
 if(mytetraConfig.getInterfaceMode()=="desktop")
 {
   insertActionAsButton(toolsLine, actionEditField);
   insertActionAsButton(toolsLine, actionDelete);
 }

 toolsLine->addSeparator();
 insertActionAsButton(toolsLine, actionCut);
 insertActionAsButton(toolsLine, actionCopy);
 insertActionAsButton(toolsLine, actionPaste);
 toolsLine->addSeparator();
 insertActionAsButton(toolsLine, actionMoveUp);
 insertActionAsButton(toolsLine, actionMoveDn);


 extraToolsLine=new QToolBar(this);

 if(mytetraConfig.getInterfaceMode()=="desktop")
 {
   insertActionAsButton(extraToolsLine, actionSyncro);
   insertActionAsButton(extraToolsLine, actionWalkHistoryPrevious);
   insertActionAsButton(extraToolsLine, actionWalkHistoryNext);
 }
 insertActionAsButton(extraToolsLine, actionFindInBase);

 treePathLabel=new QLabel(this);
 treePathLabel->setWordWrap(true);
 if(mytetraConfig.getInterfaceMode()=="desktop")
   treePathLabel->hide();
}
示例#16
0
文件: ResultLog.cpp 项目: stein1/bbk
bool ResultLog::AddResult(wxString resultname, StringValueList &row)
{
	AppConfig *ac = AppConfig::GetInstance();

	wxString maxrows;
	ac->GetValue( wxString(wxT("HISTORY_COUNT")), maxrows );
	long imax;
	maxrows.ToLong( &imax );

	Result *r = GetResults( resultname );

	if( r->GetRowCount() > imax-1 )
	{
		r->DeleteRow( 0 );
	}

	r->AddRow( row );
	return false;
}
示例#17
0
文件: main.cpp 项目: ronakdev/cv-2016
int main(int argc, char* argv[])
{
    // Create all the necessary objects (calls the default constructor for each)
    TargetDetector detector;
    TargetProcessor processor;
    NetworkController networkController;
    VideoDevice camera;
	CmdLineInterface interface(argc, argv);		
	AppConfig config = interface.getConfig();
	GUIManager gui;

	if(config.getIsDevice())
    {
        camera.startCapture(config.getDeviceID());
        if(config.getIsDebug())
            std::cout << "Camera ready!\n";
    }

    //init networking
    if(config.getIsNetworking())
        networkController.startServer();

    if(!config.getIsHeadless())
        gui.init();
    if(config.getIsDebug())
	 std::cout << "Im debugging! :D\n";

    while(true)
    {
        networkController.waitForPing();

        cv::Mat image = camera.getImage();
        Target* target = detector.processImage(image);

        bool foundTarget = (target == NULL ? false : true);

        if(foundTarget)
        {
            processor.loadTarget(target);
            double distance = processor.calculateDistance();

            networkController.sendMessage("true;" +
                boost::lexical_cast<std::string> (distance));

            std::cout << "Target Found! Distance: " << distance;
        }
        else
        {
            networkController.sendMessage("false;");
        }
    }

    return 0;
}
示例#18
0
// Действия, происходящие по таймеру
void PeriodicSyncro::timerEvent(QTimerEvent *event)
{
  Q_UNUSED(event);

  qDebug() << "In timer PeriodicSyncro working method";

  // Если команда синхронизации пуста, нечего выполнять
  if(mytetraConfig.get_synchrocommand().trimmed().length()==0)
    return;

  // Запуск синхронизации в скрытом режиме
  find_object<MainWindow>("mainwindow")->synchronization(false);
}
void TreeScreen::setupModels(void)
{
// Создание и первичная настройка модели
    knowTreeModel = new KnowTreeModel(this);

// Установка заголовка
// QStringList headers;
// headers << tr("Info groups");
// knowTreeModel->setHeaders(headers);

// Загрузка данных
    knowTreeModel->initFromXML( mytetraConfig.get_tetradir()+"/mytetra.xml" );

// Модель подключется к виду
    knowTreeView->setModel(knowTreeModel);
}
示例#20
0
void ConsoleEmulator::setupUI(void)
{
 messageLabel=new QLabel(this);

 buttonDetails=new QToolButton(this);
 buttonDetails->setIcon(QIcon(":/resource/pic/expand_console.svg"));

 buttonCancel=new QPushButton(this);
 buttonCancel->setText(tr("Cancel"));
 buttonCancel->setDefault(true);

 consoleOutput=new QTextEdit(this);
 consoleOutput->setReadOnly(true);
 consoleOutput->setFontFamily("monospace");
 if(mytetraconfig.getSyncroConsoleDetails()==false)
  consoleOutput->hide();

 waitClock=new WaitClock(this);
}
示例#21
0
void AppConfigPage_Misc::setupUi(void)
{
  qDebug() << "Create misc config page";

  // Блок настройки подтверждения для действия "cut" на ветке
  cutBranchConfirm=new QCheckBox(this);
  cutBranchConfirm->setText(tr("Confirm item cut"));
  cutBranchConfirm->setChecked(mytetraConfig.get_cutbranchconfirm());

  // Блок настройки отображения отладочных сообщений в консоли
  printDebugMessages=new QCheckBox(this);
  printDebugMessages->setText(tr("Print debug messages to console"));
  printDebugMessages->setChecked(mytetraConfig.get_printdebugmessages());

  // Настройка запуска MyTetra в свернутом окне
  runInMinimizedWindow=new QCheckBox(this);
  runInMinimizedWindow->setText(tr("Run MyTetra in a minimized window"));
  runInMinimizedWindow->setChecked(mytetraConfig.get_runinminimizedwindow());

  // Разрешение/запрещение лога действий
  enableActionLog=new QCheckBox(this);
  enableActionLog->setText(tr("Enable action logging (experimental)"));
  enableActionLog->setChecked(mytetraConfig.getEnableLogging());

  // Разрешение/запрещение создавать пустую запись (без текста)
  enableCreateEmptyRecord=new QCheckBox(this);
  enableCreateEmptyRecord->setText(tr("Create empty note enable"));
  enableCreateEmptyRecord->setChecked(mytetraConfig.getEnableCreateEmptyRecord());

  // Настройки курсора при навигации по истории
  rememberAtHistoryNavigationCheckBox=new QCheckBox(this);
  rememberAtHistoryNavigationCheckBox->setText(tr("Remember cursor position at history navigation"));
  rememberAtHistoryNavigationCheckBox->setChecked(mytetraConfig.getRememberCursorAtHistoryNavigation());

  rememberAtOrdinarySelectionCheckBox=new QCheckBox(this);
  rememberAtOrdinarySelectionCheckBox->setText(tr("Try remember cursor position at ordinary selection"));
  rememberAtOrdinarySelectionCheckBox->setChecked(mytetraConfig.getRememberCursorAtOrdinarySelection());

  // Кнопка редактирования файла конфигурации MyTetra
  editMyTetraConfigFile=new QPushButton(this);
  editMyTetraConfigFile->setText(tr("Edit config file"));
  editMyTetraConfigFile->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed, QSizePolicy::ToolButton));
}
示例#22
0
// Метод должен возвращать уровень сложности сделанных изменений
// 0 - изменения не требуют перезапуска программы
// 1 - изменения требуют перезапуска программы
int AppConfigPage_Misc::applyChanges(void)
{
  qDebug() << "Apply changes misc";

  int result=0;

  // Сохраняется настройка подтверждения для действия "cut" на ветке
  if(mytetraConfig.get_cutbranchconfirm()!=cutBranchConfirm->isChecked())
    mytetraConfig.set_cutbranchconfirm(cutBranchConfirm->isChecked());

  // Сохраняется настройка отображения отладочных сообщений в консоли
  if(mytetraConfig.get_printdebugmessages()!=printDebugMessages->isChecked())
    mytetraConfig.set_printdebugmessages(printDebugMessages->isChecked());

  // Сохраняется настройка режима запуска MyTetra - обычный или свернутый
  if(mytetraConfig.get_runinminimizedwindow()!=runInMinimizedWindow->isChecked())
    mytetraConfig.set_runinminimizedwindow(runInMinimizedWindow->isChecked());

  // Сохраняется настройка разрешения/запрещения лога действий
  if(mytetraConfig.getEnableLogging()!=enableActionLog->isChecked())
  {
    mytetraConfig.setEnableLogging(enableActionLog->isChecked());
    result=1;
  }

  // Сохраняется настройка возможности создания записи, не содержащей текст
  if(mytetraConfig.getEnableCreateEmptyRecord()!=enableCreateEmptyRecord->isChecked())
    mytetraConfig.setEnableCreateEmptyRecord(enableCreateEmptyRecord->isChecked());

  // Сохраняется настройка нужно ли вспоминать позицию курсора при перемещении
  // по истории
  if(mytetraConfig.getRememberCursorAtHistoryNavigation()!=rememberAtHistoryNavigationCheckBox->isChecked())
    mytetraConfig.setRememberCursorAtHistoryNavigation(rememberAtHistoryNavigationCheckBox->isChecked());

  // Сохраняется настройка нужно ли пытаться вспоминать позицию курсора при
  // обычном выборе записи
  if(mytetraConfig.getRememberCursorAtOrdinarySelection()!=rememberAtOrdinarySelectionCheckBox->isChecked())
    mytetraConfig.setRememberCursorAtOrdinarySelection(rememberAtOrdinarySelectionCheckBox->isChecked());

  return result;
}
示例#23
0
int main(int argc, char* argv[])
{
    // Create all the necessary objects (calls the default constructor for each)
    TargetDetector detector;
    TargetProcessor processor;
    NetworkController networkController;
    VideoDevice camera;
	CmdLineInterface interface(argc, argv);
	AppConfig config = interface.getConfig();
	//GUIManager gui;

	if(config.getIsDevice()){
        camera.startCapture(config.getDeviceID());
        if(config.getIsDebug())
            std::cout << "Camera ready!\n";
    }

    //init networking
    if(config.getIsNetworking())
        networkController.startServer();

    //if(!config.getIsHeadless())
    //    gui.init();
    if(config.getIsDebug())
	 	std::cout << "Im debugging! :D\n";
    cv::Mat image;

    //debug
    int loop = 1;
    cv::namedWindow("Live Video Feed", cv::WINDOW_NORMAL);
    cv::namedWindow("General", cv::WINDOW_NORMAL);


    while(cv::waitKey(30) != 27)
    {
        Mat background(Size(1000,1000), CV_8UC1, Scalar(255, 255, 255 ));

        if(config.getIsDebug())
            std::cout << "While Loop #" << loop << std::endl;

		if(config.getIsNetworking())
        	networkController.waitForPing();

        image = camera.getImage();
        if(!image.data) // check if image is valid
        {
            if(config.getIsDebug())
                std::cout << "failed to read image" << std::endl;
            return -1;
        }

        if(config.getIsDebug())
            std::cout << "Image Read" << std::endl;
        Target* target = detector.processImage(image);

        if(config.getIsDebug())
            std::cout << "Image Processed by Target Detector" << std::endl;
        /*
        (std::cout << "Target Value:" << target << "End of Target Value\n";
        std::cout << "CR A OW: " << target-> crow;
        target -> printPoints();
        */
        bool foundTarget = false;
        if (target != NULL)
        {
            foundTarget = true;
            image = detector.getOutlinedImage();
        }
        std::cout <<"About to check the value of foundTarget" << std::endl;
        if(foundTarget)
        {


            std::cout <<"Target was found " << std::endl;

            if(config.getIsDebug())
                std::cout << "Image Being Processed" << std::endl;

            processor.loadTarget(target);

            if(config.getIsDebug())
                std::cout << "Target Loaded" << std::endl;

            double distance = processor.calculateDistance();

            if(config.getIsDebug())
                std::cout << "Distance Calculated" << std::endl;

			double azimuth = processor.calculateAzimuth();
            if(config.getIsDebug())
                std::cout << "Azimuth Calculated" << std::endl;

			double altitude = processor.calculateAltitude();
            if(config.getIsDebug())
                std::cout << "Altitude Calculated" << std::endl;

            if(config.getIsDebug())
                std::cout << "Image Processed by TargetProcessor" << std::endl;

                std::string dis = "distance: " + std::to_string(distance);
                std::string alt = "altitude: " + std::to_string(altitude);
                std::string azi = "azimuth: " + std::to_string(azimuth);  

                cv::putText(background, dis, cv::Point(50,100),
                cv::FONT_HERSHEY_COMPLEX_SMALL, 2, cv::Scalar(0, 255, 0),
                1);

                cv::putText(background, alt, cv::Point(50,200),
                cv::FONT_HERSHEY_COMPLEX_SMALL, 2, cv::Scalar(0, 255, 0),
                1);

                cv::putText(background, azi, cv::Point(50,400),
                cv::FONT_HERSHEY_COMPLEX_SMALL, 2, cv::Scalar(0, 255, 0),
                1);

                imshow("General", background);

                if (config.getIsNetworking())
			    {
		            networkController.sendMessage("true;" +
		            boost::lexical_cast<std::string> (distance) + ";" +
					boost::lexical_cast<std::string> (azimuth) + ";" +
					boost::lexical_cast<std::string> (altitude));
			}

			if(config.getIsDebug()){
            	std::cout << "Target Found! Distance: " << distance;
                std::cout << "Altitude: " << altitude << std::endl;
                std::cout << "Azimuth: " << azimuth << std::endl;
            }

        }
        else
        {
            if (config.getIsNetworking())
                networkController.sendMessage("false;");
        }
        imshow("Live Video Feed", image);


        loop++;
        delete target;
    }

    return 0;
}
示例#24
0
Sample::Sample(long nr) : nr(nr) {
	AppConfig *config = AppConfig::getInstance();
	nrRows = config->getSampleRows();
	nrColumns = config->getSampleColumns();
	entries = new math::Vector[nrRows * nrColumns];
}
示例#25
0
// Переопределяемый метод
bool PeriodicSyncro::isStartEnabled()
{
  return mytetraConfig.getEnablePeriodicSyncro();
}
示例#26
0
// Метод должен возвращать уровень сложности сделанных изменений
// 0 - изменения не требуют перезапуска программы
// 1 - изменения требуют перезапуска программы
int AppConfigPage_Main::applyChanges(void)
{
 qDebug() << "Apply changes main";
 
 int difficultChanges=0;
 
 // Если был изменен путь к базе, он запоминается в конфигфайл
 if(mytetraConfig.get_tetradir()!=tetradirInput->text())
  {
   QDir dir(tetradirInput->text());

   // Проверяется, допустимо ли имя директории
   if(dir.isReadable()==false || dir.exists()==false)
    QMessageBox::warning(this, tr("Warning"),
                               tr("The data directory does not exists or unavailable for reading."),
                               QMessageBox::Ok); 
   else
    { 
     // Новое имя запоминается в конфиг
     mytetraConfig.set_tetradir(tetradirInput->text());
     difficultChanges=1;
    } 
  } 

 
 // Если был изменен путь к корзине, он запоминается в конфигфайл
 if(mytetraConfig.get_trashdir()!=trashdirInput->text())
  {
   QDir dir(trashdirInput->text());

   // Проверяется, допустимо ли имя директории
   if(dir.isReadable()==false || dir.exists()==false)
    QMessageBox::warning(this, tr("Warning"),
                               tr("The trash directory does not exists or unavailable for reading."),
                               QMessageBox::Ok); 
   else
    { 
     // Новое имя запоминается в конфиг
     mytetraConfig.set_trashdir(trashdirInput->text());
    } 
  } 
 
 
 // Если был изменен размер корзины
 if( (int)mytetraConfig.get_trashsize() != (int)trashsizeInput->text().toInt() )
  {
   mytetraConfig.set_trashsize(trashsizeInput->text().toInt());
  }

 
 // Если было изменено максимально возможное количество файлов в корзине
 if(mytetraConfig.get_trashmaxfilecount()!=trashmaxfilecountInput->text().toInt())
  {
   mytetraConfig.set_trashmaxfilecount(trashmaxfilecountInput->text().toInt());
  }


 // Если было изменено использование пользовательского формата даты и времени
 if(mytetraConfig.getEnableCustomDateTimeFormat()!=enableCustomDateTimeFormat->isChecked())
  {
   mytetraConfig.setEnableCustomDateTimeFormat(enableCustomDateTimeFormat->isChecked());
  }


 // Если было изменен пользовательский формат даты и времени
 if(mytetraConfig.getCustomDateTimeFormat()!=customDateTimeFormat->text())
  {
   mytetraConfig.setCustomDateTimeFormat(customDateTimeFormat->text());
  }

 
 // Если был изменен язык
 if(mytetraConfig.get_interfacelanguage()!=interfaceLanguage->currentText())
  {
   mytetraConfig.set_interfacelanguage(interfaceLanguage->currentText());
   difficultChanges=1;
  }

 return difficultChanges;
}
示例#27
0
void AppConfigPage_Main::setupUi(void)
{
 qDebug() << "Create main config page";
 
 // Блок работы с путем до каталога данных
 tetradirLabel=new QLabel(this);
 tetradirLabel->setText(tr("Data directory"));

 tetradirInput=new QLineEdit(this);
 tetradirInput->setMinimumWidth(50);
 tetradirInput->setText(mytetraConfig.get_tetradir());

 tetradirButton=new QToolButton(this);
 tetradirButton->setText(tr("..."));


 // Блок работы с путем до корзины
 trashdirLabel=new QLabel(this);
 trashdirLabel->setText(tr("Trash directory"));

 trashdirInput=new QLineEdit(this);
 trashdirInput->setMinimumWidth(50);
 trashdirInput->setText(mytetraConfig.get_trashdir());

 trashdirButton=new QToolButton(this);
 trashdirButton->setText(tr("..."));

 
 // Блок работы с размером корзины
 trashsizeLabel=new QLabel(this);
 trashsizeLabel->setText(tr("Trash size"));
 
 trashsizeInput=new QSpinBox(this);
 trashsizeInput->setRange(1,1000);
 trashsizeInput->setValue(mytetraConfig.get_trashsize());
 
 trashsizeFlexion=new QLabel(this);
 trashsizeFlexion->setText(tr("Mb"));


 // Блок работы с максимальным количеством файлов в корзине
 trashmaxfilecountLabel=new QLabel(this);
 trashmaxfilecountLabel->setText(tr("Maximum files in trash"));
 
 trashmaxfilecountInput=new QSpinBox(this);
 trashmaxfilecountInput->setRange(1,3000);
 trashmaxfilecountInput->setValue(mytetraConfig.get_trashmaxfilecount());
 
 trashmaxfilecountFlexion=new QLabel(this);
 trashmaxfilecountFlexion->setText(tr("files"));


 // Блок работы с выбором языка интерфейса
 interfaceLanguageLabel=new QLabel(this);
 interfaceLanguageLabel->setText(tr("Language"));

 interfaceLanguage=new MtComboBox(this);
 interfaceLanguage->setMinimumContentsLength(2);
 interfaceLanguage->addItem("en");
 interfaceLanguage->addItem("ru");
 interfaceLanguage->setCurrentIndex(interfaceLanguage->findText(mytetraConfig.get_interfacelanguage(), Qt::MatchCaseSensitive));


 // Блок работы с отображением даты и времени
 dateTimeFormatBox=new QGroupBox(this);
 dateTimeFormatBox->setTitle(tr("Displaying date and time format"));

 disableCustomDateTimeFormat=new QRadioButton(tr("Locale settings"));
 enableCustomDateTimeFormat=new QRadioButton(tr("Custom format"));
 customDateTimeFormat=new QLineEdit();
 dateTimeFormatHelpButton=new QToolButton();
 QCommonStyle styleHelp;
 dateTimeFormatHelpButton->setIcon( styleHelp.standardIcon(QStyle::SP_MessageBoxQuestion) );

 // Точка устанавливается возле того пункта, который настроен в конфиге
 if(mytetraConfig.getEnableCustomDateTimeFormat()==false)
 {
   disableCustomDateTimeFormat->setChecked(true);
   enableCustomDateTimeFormat->setChecked(false);
   customDateTimeFormat->setEnabled(false);
 }
 else
 {
   // Если разрешен пользовательский формат даты и времени
   disableCustomDateTimeFormat->setChecked(false);
   enableCustomDateTimeFormat->setChecked(true);
   customDateTimeFormat->setEnabled(true);
   customDateTimeFormat->setText( mytetraConfig.getCustomDateTimeFormat() );
 }

}
示例#28
0
Win32UserWindow::Win32UserWindow(SharedUIBinding binding, WindowConfig* config, SharedUserWindow& parent) :
	UserWindow(binding, config, parent),
	script_evaluator(binding->GetHost()),
	menuBarHandle(NULL),
	menuInUse(NULL),
	menu(NULL),
	contextMenuHandle(NULL),
	initial_icon(NULL),
	web_inspector(NULL)
{
	static bool initialized = false;
	win32_host = static_cast<kroll::Win32Host*>(binding->GetHost());
	if (!initialized) {
		INITCOMMONCONTROLSEX InitCtrlEx;

		InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
		InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES;
		InitCommonControlsEx(&InitCtrlEx);

		curl_register_local_handler(&Titanium_app_url_handler);
		curl_register_local_handler(&Titanium_ti_url_handler);
		addScriptEvaluator(&script_evaluator);
	}

	Win32UserWindow::RegisterWindowClass(win32_host->GetInstanceHandle());
	window_handle
			= CreateWindowEx(WS_EX_LAYERED, windowClassName,
					config->GetTitle().c_str(), WS_CLIPCHILDREN, CW_USEDEFAULT,
					0, CW_USEDEFAULT, 0, NULL, NULL,
					win32_host->GetInstanceHandle(), NULL);

	if (window_handle == NULL) {
		std::cout << "Error Creating Window: " << GetLastError() << std::endl;
	}
	std::cout << "window_handle = " << (int) window_handle << std::endl;

	// make our HWND available to 3rd party devs without needing our headers
	SharedValue windowHandle = Value::NewVoidPtr((void*) window_handle);
	this->Set("windowHandle", windowHandle);
	this->SetMethod("addMessageHandler", &Win32UserWindow::AddMessageHandler);

	SetWindowUserData(window_handle, this);

	this->ReloadTiWindowConfig();
	this->SetupDecorations(false);

	Bounds b;
	b.x = config->GetX();
	b.y = config->GetY();
	b.width = config->GetWidth();
	b.height = config->GetHeight();
	SetBounds(b);

	//web_view = WebView::createInstance();
	HRESULT hr = CoCreateInstance(CLSID_WebView, 0, CLSCTX_ALL, IID_IWebView,
			(void**) &web_view);
	if (FAILED(hr)) {
		std::cerr << "Error Creating WebView: ";
		if (hr == REGDB_E_CLASSNOTREG)
			std::cerr << "REGDB_E_CLASSNOTREG" << std::endl;
		else if (hr == CLASS_E_NOAGGREGATION)
			std::cerr << "CLASS_E_NOAGGREGATION" << std::endl;
		else if (hr == E_NOINTERFACE)
			std::cerr << "E_NOINTERFACE" << std::endl;
		else if (hr == E_UNEXPECTED)
			std::cerr << "E_UNEXPECTED" << std::endl;
		else if (hr == E_OUTOFMEMORY)
			std::cerr << "E_OUTOFMEMORY" << std::endl;
		else if (hr == E_INVALIDARG)
			std::cerr << "E_INVALIDARG" << std::endl;
		else
			fprintf(stderr, "Unknown Error? %x\n", hr);
	}

	// set the custom user agent for Titanium
	double version = host->GetGlobalObject()->Get("version")->ToDouble();
	char userAgent[128];
	sprintf(userAgent, "%s/%0.2f", PRODUCT_NAME, version);
	_bstr_t ua(userAgent);
	web_view->setApplicationNameForUserAgent(ua.copy());

	// place our user agent string in the global so we can later use it
	SharedBoundObject global = host->GetGlobalObject();
	_bstr_t uaurl("http://titaniumapp.com");
	BSTR uaresp;
	web_view->userAgentForURL(uaurl.copy(), &uaresp);
	std::string ua_str = _bstr_t(uaresp);
	global->Set("userAgent", Value::NewString(ua_str.c_str()));

	std::cout << "create frame load delegate " << std::endl;
	frameLoadDelegate = new Win32WebKitFrameLoadDelegate(this);
	uiDelegate = new Win32WebKitUIDelegate(this);
	policyDelegate = new Win32WebKitPolicyDelegate(this);

	std::cout << "set delegates, set host window, webview=" << (int) web_view
			<< std::endl;
	hr = web_view->setFrameLoadDelegate(frameLoadDelegate);
	hr = web_view->setUIDelegate(uiDelegate);
	hr = web_view->setPolicyDelegate(policyDelegate);
	hr = web_view->setHostWindow((OLE_HANDLE) window_handle);

	std::cout << "init with frame" << std::endl;
	RECT client_rect;
	GetClientRect(window_handle, &client_rect);
	hr = web_view->initWithFrame(client_rect, 0, 0);

	AppConfig *appConfig = AppConfig::Instance();
	std::string appid = appConfig->GetAppID();

	IWebPreferences *prefs = NULL;
	hr = CoCreateInstance(CLSID_WebPreferences, 0, CLSCTX_ALL,
			IID_IWebPreferences, (void**) &prefs);
	if (FAILED(hr) || prefs == NULL) {
		std::cerr << "Couldn't create the preferences object" << std::endl;
	} else {
		_bstr_t pi(appid.c_str());
		prefs->initWithIdentifier(pi.copy(), &prefs);

		prefs->setCacheModel(WebCacheModelDocumentBrowser);
		prefs->setPlugInsEnabled(true);
		prefs->setJavaEnabled(true);
		prefs->setJavaScriptEnabled(true);
		prefs->setDOMPasteAllowed(true);

		IWebPreferencesPrivate* privatePrefs = NULL;
		hr = prefs->QueryInterface(IID_IWebPreferencesPrivate,
				(void**) &privatePrefs);
		if (FAILED(hr)) {
			std::cerr << "Failed to get private preferences" << std::endl;
		} else {
			privatePrefs->setDeveloperExtrasEnabled(host->IsDebugMode());
			//privatePrefs->setDeveloperExtrasEnabled(host->IsDebugMode());
			privatePrefs->setDatabasesEnabled(true);
			privatePrefs->setLocalStorageEnabled(true);
			privatePrefs->setOfflineWebApplicationCacheEnabled(true);

			_bstr_t db_path(
					FileUtils::GetApplicationDataDirectory(appid).c_str());
			privatePrefs->setLocalStorageDatabasePath(db_path.copy());
			privatePrefs->Release();
		}

		web_view->setPreferences(prefs);
		prefs->Release();
	}

	// allow app:// and ti:// to run with local permissions (cross-domain ajax,etc)
	_bstr_t app_proto("app");
	web_view->registerURLSchemeAsLocal(app_proto.copy());

	_bstr_t ti_proto("ti");
	web_view->registerURLSchemeAsLocal(ti_proto.copy());

	IWebViewPrivate *web_view_private;
	hr = web_view->QueryInterface(IID_IWebViewPrivate,
			(void**) &web_view_private);
	hr = web_view_private->viewWindow((OLE_HANDLE*) &view_window_handle);

	hr = web_view_private->inspector(&web_inspector);
	if (FAILED(hr) || web_inspector == NULL) {
		std::cerr << "Couldn't retrieve the web inspector object" << std::endl;
	}

	web_view_private->Release();

	_bstr_t inspector_url("ti://com.titaniumapp/runtime/inspector/inspector.html");
	_bstr_t localized_strings_url("ti://com.titaniumapp/runtime/inspector/localizedStrings.js");
	web_inspector->setInspectorURL(inspector_url.copy());
	web_inspector->setLocalizedStringsURL(localized_strings_url.copy());

	hr = web_view->mainFrame(&web_frame);
	//web_view->setShouldCloseWithWindow(TRUE);

	std::cout << "resize subviews" << std::endl;
	ResizeSubViews();

	// ensure we have valid restore values
	restore_bounds = GetBounds();
	restore_styles = GetWindowLong(window_handle, GWL_STYLE);

	if (this->config->IsFullScreen()) {
		this->SetFullScreen(true);
	}

	if (this->config->IsTopMost() && this->config->IsVisible()) {
		this->SetTopMost(true);
	}

	// set this flag to indicate that when the frame is loaded
	// we want to show the window - we do this to prevent white screen
	// while the URL is being fetched
	this->requires_display = true;

	// set initial window icon to icon associated with exe file
	char exePath[MAX_PATH];
	GetModuleFileNameA(GetModuleHandle(NULL), exePath, MAX_PATH);
	initial_icon = ExtractIcon(win32_host->GetInstanceHandle(), exePath, 0);
	if (initial_icon) {
		SendMessageA(window_handle, (UINT) WM_SETICON, ICON_BIG,
				(LPARAM) initial_icon);
	}
}
void RecordTableController::initMetaEditorAtClickToRecord(const int pos)
{
    // Внимание! Наверно, всю эту логику следует перенести в MetaEditor. А здесь только получить данные из таблицы

    // Выясняется указатель на объект редактирования текста записи
    MetaEditor *edView=find_object<MetaEditor>("editorScreen");

    // Выясняется ссылка на таблицу конечных данных
    RecordTableData *table=recordSourceModel->getTableData();

    // В таблице конечных данных запоминается какая запись была выбрана
    // чтобы затем при выборе этой же подветки засветка автоматически
    // установилась на последнюю рабочую запись
    table->setWorkPos( pos );


    // Устанавливается функция обратного вызова для записи данных
    edView->set_save_callback(table->editorSaveCallback);

    // Сохраняется текст и картинки в окне редактирования
    find_object<MainWindow>("mainwindow")->saveTextarea();


    // Для новой выбраной записи выясняется директория и основной файл
    QString currentDir =table->getField("dir", pos);
    QString currentFile=table->getField("file", pos);
    QString fullDir=mytetraConfig.get_tetradir()+"/base/"+currentDir;
    QString fullFileName=fullDir+"/"+currentFile;
    qDebug() << " File " << fullFileName << "\n";

    // Если в окне содержимого записи уже находится выбираемая запись
    if(edView->get_work_directory()==fullDir &&
            edView->get_file_name()==currentFile) {
        globalParameters.getWindowSwitcher()->switchFromRecordtableToRecord();
        return;
    }

    // Перед открытием редактора происходит попытка получения текста записи
    // Этот вызов создаст файл с текстом записи, если он еще не создан (подумать, переделать)
    table->getText(pos);

    // Редактору задаются имя файла и директории
    // И дается команда загрузки файла
    edView->set_work_directory(fullDir);
    edView->set_file_name(currentFile);

    // Если идет работа с зашифрованной записью
    // И если имя директории или имя файла пусты, то это означает что
    // запись не была расшифрована, и редактор должен просто показывать пустой текст
    // ничего не сохранять и не считывать
    qDebug() << "RecordTableView::onClickToRecord() : id " << table->getField("id", pos);
    qDebug() << "RecordTableView::onClickToRecord() : name " << table->getField("name", pos);
    qDebug() << "RecordTableView::onClickToRecord() : crypt " << table->getField("crypt", pos);
    if(table->getField("crypt", pos)=="1")
        if(fullDir.length()==0 || currentFile.length()==0)
            edView->setDirFileEmptyReaction(MetaEditor::DIRFILEEMPTY_REACTION_SUPPRESS_ERROR);

    // В редактор заносится информация, идет ли работа с зашифрованным текстом
    edView->setMiscField("crypt", table->getField("crypt", pos));

    // В редакторе устанавливается функция обратного вызова для чтения данных
    edView->set_load_callback(table->editorLoadCallback);

    edView->load_textarea();
    // edView->set_textarea(table->get_text(index.row()));

    // Заполняются прочие инфо-поля
    edView->setName  ( table->getField("name", pos) );
    edView->setAuthor( table->getField("author", pos) );
    edView->setUrl   ( table->getField("url", pos) );
    edView->setTags  ( table->getField("tags", pos) );

    QString id=table->getField("id", pos);
    edView->setMiscField("id", id);

    edView->setMiscField( "title", table->getField("name", pos) );

    // Устанавливается путь до ветки в которой лежит запись (в виде названий веток)
    QString path=qobject_cast<RecordTableScreen *>(parent())->getTreePath();

    // В мобильном интерфейсе редактор должен показывать путь до записи
    if(mytetraConfig.getInterfaceMode()=="mobile")
        edView->setTreePath( path );

    // В редакторе восстанавливается позиция курсора и прокрутки если это необходимо
    if(mytetraConfig.getRememberCursorAtOrdinarySelection()) {
        edView->setCursorPosition( walkHistory.getCursorPosition(id) );
        edView->setScrollBarPosition( walkHistory.getScrollBarPosition(id) );
    }

    // Обновление иконки аттачей
    if( table->getRecord(pos)->getAttachTablePointer()->size()==0 )
        edView->toAttach->setIcon( edView->iconAttachNotExists ); // Если нет приаттаченных файлов
    else
        edView->toAttach->setIcon( edView->iconAttachExists ); // Есть приаттаченные файлы
}
示例#30
0
int main(int argc, char* argv[])
{
    // get command line interface config options
    CmdLineInterface interface(argc, argv);
    AppConfig config = interface.getConfig();

    GUIManager gui;
    VideoDevice camera;
    LProcessor processor;
    NetworkController networkController;
    ArduinoController arduino;

    //init camera
    if(config.getIsDevice())
    {
        camera.startCapture(config.getDeviceID());
        if(config.getIsDebug())
            std::cout << "Camera ready!\n";
    }

    //init networking
    if(config.getIsNetworking())
        networkController.startServer();

    if(!config.getIsHeadless())
        gui.init();

    if (config.getHasArduino())
    {
        //16 is /dev/ttyUSB0, 24 is /dev/ttyACM0
        arduino.init(9600, 24);  //baud rate, serial port
    }
    //continuous server loop
    do
    {
        if(config.getIsNetworking())
            networkController.waitForPing();

        LDetector detector;

        cv::Mat image;
        if(config.getIsFile());
            //image = cv::imread(config.getFileName());
        //else
        //    image = camera.getImage(config.getIsDebug());

        //detector.elLoad(image);
        //detector.elSplit();
        //detector.elThresh();
        //detector.elContours(); detector.elFilter();

        bool foundL = true;
        if (detector.getLs().size() > 0)
            detector.largest2();
        else
            foundL = false;
        if (detector.getLs().size() == 0)
            foundL = false;
        if (foundL)
        {
            processor.determineL(detector.getLs());
            processor.determineAzimuth();
            processor.determineDistance();
            double azimuth = processor.getAzimuth();
            double distance = processor.getDistance();

            if(config.getIsDebug())
            {
                processor.outputData();
                std::cout << "Final distance (m): " << processor.getDistance() << std::endl;
            }

            if(!config.getIsHeadless())
            {
                int i_dist = (int) (distance * 1000.0);
                int dist_left = i_dist / 1000;
                int dist_right = i_dist % 1000;
                std::string dist_str = boost::lexical_cast<std::string>(dist_left) + "." + boost::lexical_cast<std::string>(dist_right);

                gui.setImage(detector.show());
                gui.setImageText("Distance: " + dist_str + " m");
                gui.show(config.getIsFile());
            }

            if(config.getIsNetworking())
            {
                networkController.sendMessage(boost::lexical_cast<std::string> ("true") + std::string(";")
                                              + boost::lexical_cast<std::string> (distance) + std::string(";")
                                              + boost::lexical_cast<std::string> (azimuth));
            }

        }
        else
        {
            if(config.getIsNetworking())
                networkController.sendMessage(boost::lexical_cast<std::string> ("false") + std::string(";"));
            if(!config.getIsHeadless())
            {
                gui.setImage(detector.show());
                gui.setImageText("No L's Found");
                gui.show(config.getIsFile());
            }
        }

        if(config.getHasArduino())
        {
            char c = std::rand() % 26 + 'A';
            arduino.sendMessage(c, cv::Point(5, 5));
            cv::waitKey(300);
        }

    }
    while(config.getIsDevice());

    return 0;
}