void KateApp::restoreKate () { // restore the nice files ;) we need it Kate::Document::setOpenErrorDialogsActivated (false); // activate again correct session!!! sessionConfig()->setGroup("General"); QString lastSession (sessionConfig()->readEntry ("Last Session", "default.katesession")); sessionManager()->activateSession (new KateSession (sessionManager(), lastSession, ""), false, false, false); m_docManager->restoreDocumentList (sessionConfig()); Kate::Document::setOpenErrorDialogsActivated (true); // restore all windows ;) for (int n=1; KMainWindow::canBeRestored(n); n++) newMainWindow(sessionConfig(), QString ("%1").arg(n)); // oh, no mainwindow, create one, should not happen, but make sure ;) if (mainWindows() == 0) newMainWindow (); // notify about start KStartupInfo::setNewStartupId( activeMainWindow(), startupId()); }
// GET param: // - hash (string): torrent hash // - rid (int): last response id void SyncController::torrentPeersAction() { auto lastResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastResponse")).toMap(); auto lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncTorrentPeersLastAcceptedResponse")).toMap(); const QString hash {params()["hash"]}; BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (!torrent) throw APIError(APIErrorType::NotFound); QVariantMap data; QVariantHash peers; const QList<BitTorrent::PeerInfo> peersList = torrent->peers(); #ifndef DISABLE_COUNTRIES_RESOLUTION bool resolvePeerCountries = Preferences::instance()->resolvePeerCountries(); #else bool resolvePeerCountries = false; #endif data[KEY_SYNC_TORRENT_PEERS_SHOW_FLAGS] = resolvePeerCountries; for (const BitTorrent::PeerInfo &pi : peersList) { if (pi.address().ip.isNull()) continue; QVariantMap peer; #ifndef DISABLE_COUNTRIES_RESOLUTION if (resolvePeerCountries) { peer[KEY_PEER_COUNTRY_CODE] = pi.country().toLower(); peer[KEY_PEER_COUNTRY] = Net::GeoIPManager::CountryName(pi.country()); } #endif peer[KEY_PEER_IP] = pi.address().ip.toString(); peer[KEY_PEER_PORT] = pi.address().port; peer[KEY_PEER_CLIENT] = pi.client(); peer[KEY_PEER_PROGRESS] = pi.progress(); peer[KEY_PEER_DOWN_SPEED] = pi.payloadDownSpeed(); peer[KEY_PEER_UP_SPEED] = pi.payloadUpSpeed(); peer[KEY_PEER_TOT_DOWN] = pi.totalDownload(); peer[KEY_PEER_TOT_UP] = pi.totalUpload(); peer[KEY_PEER_CONNECTION_TYPE] = pi.connectionType(); peer[KEY_PEER_FLAGS] = pi.flags(); peer[KEY_PEER_FLAGS_DESCRIPTION] = pi.flagsDescription(); peer[KEY_PEER_RELEVANCE] = pi.relevance(); peer[KEY_PEER_FILES] = torrent->info().filesForPiece(pi.downloadingPieceIndex()).join(QLatin1String("\n")); peers[pi.address().ip.toString() + ':' + QString::number(pi.address().port)] = peer; } data["peers"] = peers; const int acceptedResponseId {params()["rid"].toInt()}; setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); sessionManager()->session()->setData(QLatin1String("syncTorrentPeersLastResponse"), lastResponse); sessionManager()->session()->setData(QLatin1String("syncTorrentPeersLastAcceptedResponse"), lastAcceptedResponse); }
// The function returns the changed data from the server to synchronize with the web client. // Return value is map in JSON format. // Map contain the key: // - "Rid": ID response // Map can contain the keys: // - "full_update": full data update flag // - "torrents": dictionary contains information about torrents. // - "torrents_removed": a list of hashes of removed torrents // - "categories": map of categories info // - "categories_removed": list of removed categories // - "server_state": map contains information about the state of the server // The keys of the 'torrents' dictionary are hashes of torrents. // Each value of the 'torrents' dictionary contains map. The map can contain following keys: // - "name": Torrent name // - "size": Torrent size // - "progress": Torrent progress // - "dlspeed": Torrent download speed // - "upspeed": Torrent upload speed // - "priority": Torrent priority (-1 if queuing is disabled) // - "num_seeds": Torrent seeds connected to // - "num_complete": Torrent seeds in the swarm // - "num_leechs": Torrent leechers connected to // - "num_incomplete": Torrent leechers in the swarm // - "ratio": Torrent share ratio // - "eta": Torrent ETA // - "state": Torrent state // - "seq_dl": Torrent sequential download state // - "f_l_piece_prio": Torrent first last piece priority state // - "completion_on": Torrent copletion time // - "tracker": Torrent tracker // - "dl_limit": Torrent download limit // - "up_limit": Torrent upload limit // - "downloaded": Amount of data downloaded // - "uploaded": Amount of data uploaded // - "downloaded_session": Amount of data downloaded since program open // - "uploaded_session": Amount of data uploaded since program open // - "amount_left": Amount of data left to download // - "save_path": Torrent save path // - "completed": Amount of data completed // - "max_ratio": Upload max share ratio // - "max_seeding_time": Upload max seeding time // - "ratio_limit": Upload share ratio limit // - "seeding_time_limit": Upload seeding time limit // - "seen_complete": Indicates the time when the torrent was last seen complete/whole // - "last_activity": Last time when a chunk was downloaded/uploaded // - "total_size": Size including unwanted data // Server state map may contain the following keys: // - "connection_status": connection status // - "dht_nodes": DHT nodes count // - "dl_info_data": bytes downloaded // - "dl_info_speed": download speed // - "dl_rate_limit: download rate limit // - "up_info_data: bytes uploaded // - "up_info_speed: upload speed // - "up_rate_limit: upload speed limit // - "queueing": priority system usage flag // - "refresh_interval": torrents table refresh interval // - "free_space_on_disk": Free space on the default save path // GET param: // - rid (int): last response id void SyncController::maindataAction() { auto lastResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastResponse")).toMap(); auto lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastAcceptedResponse")).toMap(); QVariantMap data; QVariantHash torrents; BitTorrent::Session *const session = BitTorrent::Session::instance(); for (BitTorrent::TorrentHandle *const torrent : asConst(session->torrents())) { QVariantMap map = serialize(*torrent); map.remove(KEY_TORRENT_HASH); // Calculated last activity time can differ from actual value by up to 10 seconds (this is a libtorrent issue). // So we don't need unnecessary updates of last activity time in response. if (lastResponse.contains("torrents") && lastResponse["torrents"].toHash().contains(torrent->hash()) && lastResponse["torrents"].toHash()[torrent->hash()].toMap().contains(KEY_TORRENT_LAST_ACTIVITY_TIME)) { uint lastValue = lastResponse["torrents"].toHash()[torrent->hash()].toMap()[KEY_TORRENT_LAST_ACTIVITY_TIME].toUInt(); if (qAbs(static_cast<int>(lastValue - map[KEY_TORRENT_LAST_ACTIVITY_TIME].toUInt())) < 15) map[KEY_TORRENT_LAST_ACTIVITY_TIME] = lastValue; } torrents[torrent->hash()] = map; } data["torrents"] = torrents; QVariantHash categories; const auto categoriesList = session->categories(); for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) { const auto key = it.key(); categories[key] = QVariantMap { {"name", key}, {"savePath", it.value()} }; } data["categories"] = categories; QVariantMap serverState = getTranserInfo(); serverState[KEY_TRANSFER_FREESPACEONDISK] = getFreeDiskSpace(); serverState[KEY_SYNC_MAINDATA_QUEUEING] = session->isQueueingSystemEnabled(); serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = session->isAltGlobalSpeedLimitEnabled(); serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = session->refreshInterval(); data["server_state"] = serverState; const int acceptedResponseId {params()["rid"].toInt()}; setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse))); sessionManager()->session()->setData(QLatin1String("syncMainDataLastResponse"), lastResponse); sessionManager()->session()->setData(QLatin1String("syncMainDataLastAcceptedResponse"), lastAcceptedResponse); }
void SearchController::resultsAction() { checkParams({"id"}); const int id = params()["id"].toInt(); int limit = params()["limit"].toInt(); int offset = params()["offset"].toInt(); const auto searchHandlers = sessionManager()->session()->getData<SearchHandlerDict>(SEARCH_HANDLERS); if (!searchHandlers.contains(id)) throw APIError(APIErrorType::NotFound); const SearchHandlerPtr searchHandler = searchHandlers[id]; const QList<SearchResult> searchResults = searchHandler->results(); const int size = searchResults.size(); if (offset > size) throw APIError(APIErrorType::Conflict, tr("Offset is out of range")); // normalize values if (offset < 0) offset = size + offset; if (offset < 0) // check again throw APIError(APIErrorType::Conflict, tr("Offset is out of range")); if (limit <= 0) limit = -1; if ((limit > 0) || (offset > 0)) setResult(getResults(searchResults.mid(offset, limit), searchHandler->isActive(), size)); else setResult(getResults(searchResults, searchHandler->isActive(), size)); }
void KateApp::restoreKate () { // activate again correct session!!! QString lastSession (sessionConfig()->group("General").readEntry ("Last Session", QString())); sessionManager()->activateSession (KateSession::Ptr(new KateSession (sessionManager(), lastSession)), false, false, false); // plugins KatePluginManager::self ()->loadConfig (sessionConfig()); // restore the files we need m_docManager->restoreDocumentList (sessionConfig()); // restore all windows ;) for (int n = 1; KMainWindow::canBeRestored(n); n++) newMainWindow(sessionConfig(), QString ("%1").arg(n)); // oh, no mainwindow, create one, should not happen, but make sure ;) if (mainWindows() == 0) newMainWindow (); }
int SearchController::generateSearchId() const { const auto searchHandlers = sessionManager()->session()->getData<SearchHandlerDict>(SEARCH_HANDLERS); while (true) { const auto id = Utils::Random::rand(1, INT_MAX); if (!searchHandlers.contains(id)) return id; } }
void KateApp::shutdownKate (KateMainWindow *win) { if (!win->queryClose_internal()) return; sessionManager()->saveActiveSession(true); // cu main windows while (!m_mainWindows.isEmpty()) { // mainwindow itself calls KateApp::removeMainWindow(this) delete m_mainWindows[0]; } quit (); }
void KateApp::shutdownKate (KateMainWindow *win) { if (!win->queryClose_internal()) return; sessionManager()->saveActiveSession(true, true); // detach the dcopClient dcopClient()->detach(); // cu main windows while (!m_mainWindows.isEmpty()) delete m_mainWindows[0]; quit (); }
void SearchController::startAction() { checkParams({"pattern", "category", "plugins"}); if (!Utils::ForeignApps::pythonInfo().isValid()) throw APIError(APIErrorType::Conflict, "Python must be installed to use the Search Engine."); const QString pattern = params()["pattern"].trimmed(); const QString category = params()["category"].trimmed(); const QStringList plugins = params()["plugins"].split('|'); QStringList pluginsToUse; if (plugins.size() == 1) { const QString pluginsLower = plugins[0].toLower(); if (pluginsLower == "all") pluginsToUse = SearchPluginManager::instance()->allPlugins(); else if ((pluginsLower == "enabled") || (pluginsLower == "multi")) pluginsToUse = SearchPluginManager::instance()->enabledPlugins(); else pluginsToUse << plugins; } else { pluginsToUse << plugins; } ISession *const session = sessionManager()->session(); auto activeSearches = session->getData<QSet<int>>(ACTIVE_SEARCHES); if (activeSearches.size() >= MAX_CONCURRENT_SEARCHES) throw APIError(APIErrorType::Conflict, QString("Unable to create more than %1 concurrent searches.").arg(MAX_CONCURRENT_SEARCHES)); const auto id = generateSearchId(); const SearchHandlerPtr searchHandler {SearchPluginManager::instance()->startSearch(pattern, category, pluginsToUse)}; QObject::connect(searchHandler.data(), &SearchHandler::searchFinished, this, [session, id, this]() { searchFinished(session, id); }); QObject::connect(searchHandler.data(), &SearchHandler::searchFailed, this, [session, id, this]() { searchFailed(session, id); }); auto searchHandlers = session->getData<SearchHandlerDict>(SEARCH_HANDLERS); searchHandlers.insert(id, searchHandler); session->setData(SEARCH_HANDLERS, QVariant::fromValue(searchHandlers)); activeSearches.insert(id); session->setData(ACTIVE_SEARCHES, QVariant::fromValue(activeSearches)); const QJsonObject result = {{"id", id}}; setResult(result); }
void SearchController::deleteAction() { checkParams({"id"}); const int id = params()["id"].toInt(); ISession *const session = sessionManager()->session(); auto searchHandlers = session->getData<SearchHandlerDict>(SEARCH_HANDLERS); if (!searchHandlers.contains(id)) throw APIError(APIErrorType::NotFound); const SearchHandlerPtr searchHandler = searchHandlers[id]; searchHandler->cancelSearch(); searchHandlers.remove(id); session->setData(SEARCH_HANDLERS, QVariant::fromValue(searchHandlers)); removeActiveSearch(session, id); }
void QNetworkSessionPrivate::stop() { if (serviceConfig.isValid()) { lastError = QNetworkSession::OperationNotSupportedError; emit q->error(lastError); } else { if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { state = QNetworkSession::Closing; emit q->stateChanged(state); engine->disconnectFromId(activeConfig.identifier()); sessionManager()->forceSessionClose(activeConfig); } opened = false; isOpen = false; emit q->closed(); } }
void SearchController::statusAction() { const int id = params()["id"].toInt(); const auto searchHandlers = sessionManager()->session()->getData<SearchHandlerDict>(SEARCH_HANDLERS); if ((id != 0) && !searchHandlers.contains(id)) throw APIError(APIErrorType::NotFound); QJsonArray statusArray; const QList<int> searchIds {(id == 0) ? searchHandlers.keys() : QList<int> {id}}; for (const int searchId : searchIds) { const SearchHandlerPtr searchHandler = searchHandlers[searchId]; statusArray << QJsonObject { {"id", searchId}, {"status", searchHandler->isActive() ? "Running" : "Stopped"}, {"total", searchHandler->results().size()} }; } setResult(statusArray); }
void QNetworkSessionPrivate::syncStateWithInterface() { connect(&manager, SIGNAL(updateCompleted()), this, SLOT(networkConfigurationsChanged())); connect(&manager, SIGNAL(configurationChanged(QNetworkConfiguration)), this, SLOT(configurationChanged(QNetworkConfiguration))); connect(sessionManager(), SIGNAL(forcedSessionClose(QNetworkConfiguration)), this, SLOT(forcedSessionClose(QNetworkConfiguration))); opened = false; state = QNetworkSession::Invalid; lastError = QNetworkSession::UnknownSessionError; qRegisterMetaType<QNetworkSessionEngine::ConnectionError> ("QNetworkSessionEngine::ConnectionError"); switch (publicConfig.type()) { case QNetworkConfiguration::InternetAccessPoint: activeConfig = publicConfig; engine = getEngineFromId(activeConfig.identifier()); if (engine) { connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)), this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)), Qt::QueuedConnection); } break; case QNetworkConfiguration::ServiceNetwork: serviceConfig = publicConfig; // Defer setting engine and signals until open(). // fall through case QNetworkConfiguration::UserChoice: // Defer setting serviceConfig and activeConfig until open(). // fall through default: engine = 0; } networkConfigurationsChanged(); }
bool KateApp::startupKate () { // user specified session to open if (m_args->isSet ("startanon")) { sessionManager()->activateSession (sessionManager()->giveSession (""), false, false); } else if (m_args->isSet ("start")) { sessionManager()->activateSession (sessionManager()->giveSession (m_args->getOption("start")), false, false); } else if (!m_args->isSet( "stdin" ) && (m_args->count() == 0)) // only start session if no files specified { // let the user choose session if possible if (!sessionManager()->chooseSession ()) { kDebug() << "chooseSession returned false, exiting"; // we will exit kate now, notify the rest of the world we are done #ifdef Q_WS_X11 KStartupInfo::appStarted (startupId()); #endif return false; } } else { sessionManager()->activateSession( KateSession::Ptr(new KateSession (sessionManager(), QString())), false, false ); } // oh, no mainwindow, create one, should not happen, but make sure ;) if (mainWindows() == 0) newMainWindow (); // notify about start #ifdef Q_WS_X11 KStartupInfo::setNewStartupId( activeMainWindow(), startupId()); #endif QTextCodec *codec = m_args->isSet("encoding") ? QTextCodec::codecForName(m_args->getOption("encoding").toUtf8()) : 0; bool tempfileSet = KCmdLineArgs::isTempFileSet(); KTextEditor::Document *doc = 0; const QString codec_name = codec ? codec->name() : QString(); KateDocManager::self()->setSuppressOpeningErrorDialogs(true); QList<KUrl> urls; for (int z = 0; z < m_args->count(); z++) { // this file is no local dir, open it, else warn const bool noDir = !m_args->url(z).isLocalFile() || !QFileInfo (m_args->url(z).toLocalFile()).isDir(); if (noDir) { urls << m_args->url(z); } else { KMessageBox::sorry( activeMainWindow(), i18n("The file '%1' could not be opened: it is not a normal file, it is a folder.", m_args->url(z).url()) ); } } doc = activeMainWindow()->viewManager()->openUrls(urls, codec_name, tempfileSet); KateDocManager::self()->setSuppressOpeningErrorDialogs(false); // handle stdin input if( m_args->isSet( "stdin" ) ) { QTextStream input(stdin, QIODevice::ReadOnly); // set chosen codec if (codec) input.setCodec (codec); QString line; QString text; do { line = input.readLine(); text.append( line + '\n' ); } while( !line.isNull() ); openInput (text); } else if ( doc ) activeMainWindow()->viewManager()->activateView( doc ); if ( activeMainWindow()->viewManager()->viewCount () == 0 ) activeMainWindow()->viewManager()->activateView(m_docManager->document (0)); int line = 0; int column = 0; bool nav = false; if (m_args->isSet ("line")) { line = m_args->getOption ("line").toInt() - 1; nav = true; } if (m_args->isSet ("column")) { column = m_args->getOption ("column").toInt() - 1; nav = true; } if (nav && activeMainWindow()->viewManager()->activeView ()) activeMainWindow()->viewManager()->activeView ()->setCursorPosition (KTextEditor::Cursor (line, column)); // show the nice tips KTipDialog::showTip(activeMainWindow()); activeMainWindow()->setAutoSaveSettings(); kDebug() << "KateApplication::init finished successful"; return true; }
void CMultipleRequestsDlg::OnOK() { try { //Create session manager IQBSessionManagerPtr sessionManager(CLSID_QBSessionManager); sessionManager->OpenConnection ( APPID, APPNAME ); sessionManager->BeginSession ( "", omDontCare ); //Create message set request object IMsgSetRequestPtr requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet->Attributes->OnError = roeContinue; //Add multiple requests to the message set request object //First add customer ICustomerAddPtr customerAdd = requestMsgSet->AppendCustomerAddRq(); BuildCustomerAdd ( customerAdd ); //Add an invoice for this customer IInvoiceAddPtr invoiceAdd = requestMsgSet->AppendInvoiceAddRq(); BuildInvoiceAdd ( invoiceAdd ); //Add query request for this invoice IInvoiceQueryPtr invoiceQuery = requestMsgSet->AppendInvoiceQueryRq(); BuildInvoiceQuery( invoiceQuery); //Perform the requests requestMsgSet->Attributes->OnError = roeContinue; IMsgSetResponsePtr responseMsgSet = sessionManager->DoRequests(requestMsgSet); //Close connection because we don't need it anymore sessionManager->EndSession(); sessionManager->CloseConnection(); // Uncomment the following to see the request and response XML for debugging //_bstr_t rq = requestMsgSet->ToXMLString(); //_bstr_t rs = responseMsgSet->ToXMLString(); IResponseListPtr rsList = responseMsgSet->ResponseList; int Cnt; CString msg; IResponsePtr response; //rsList->Count is 3, because we've added 3 requests //Let's retrieve them one by one //First retrieve customer add response Cnt = 0; response = rsList->GetAt(Cnt); msg = "Response 0 " ; msg += InterpretCustomerAddResponse(response); //Retrieve invoice add response Cnt = 1; response = rsList->GetAt(Cnt); msg += "\r\nResponse 1 " ; msg += InterpretInvoiceAddResponse(response); //Retrieve invoice query response Cnt = 2; response = rsList->GetAt(Cnt); msg += "\r\nResponse 1 " ; msg += InterpretInvoiceQueryResponse(response); AfxMessageBox( msg ); } catch ( _com_error e ) { CString msg; _bstr_t desc = e.Description(); msg.Format( "Error: 0x%x %s" , e.Error(), (desc.length() > 0) ? (const char*)desc : "" ); AfxMessageBox( msg ); } EndDialog(0); }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setOrganizationName("arksaw"); app.setApplicationName("tisserver"); // Initialize settings stuff QSettings::setDefaultFormat(QSettings::IniFormat); QSettings settings; settings.setValue("port", 50000); settings.sync(); Console console; Database database; SessionManager sessionManager(0, &database); GameThread game(0, &database, &sessionManager); UdpServer udpServer; qRegisterMetaType<Packet>("Packet"); qRegisterMetaType<QHostAddress>("QHostAddress"); // Console signals/slots QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &sessionManager, SLOT(runCommand(CommandType,QStringList))); QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &game, SLOT(runCommand(CommandType,QStringList)), Qt::DirectConnection); // Need direct connection from cross-thread signals to blocked thread QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)), &udpServer, SLOT(runCommand(CommandType,QStringList))); // Database signals/slots QObject::connect(&database, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString)), Qt::QueuedConnection); // SessionManager signals/slots QObject::connect(&sessionManager, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&sessionManager, SIGNAL(responseReady(Packet,QHostAddress,quint16)), &udpServer, SLOT(sendResponse(Packet,QHostAddress,quint16)), Qt::QueuedConnection); // GameThread signals/slots QObject::connect(&game, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&game, SIGNAL(updatePacketReady(Packet)), &sessionManager, SLOT(sendUpdatePacket(Packet)), Qt::QueuedConnection); // UdpServer signals/slots QObject::connect(&udpServer, SIGNAL(writeToConsole(QString)), &console, SLOT(writeLine(QString))); QObject::connect(&udpServer, SIGNAL(packetReceived(Packet,QHostAddress,quint16)), &sessionManager, SLOT(processPacket(Packet,QHostAddress,quint16)), Qt::DirectConnection); // Set up threading. QThread thread; game.moveToThread(&thread); thread.start(); thread.connect(&thread, SIGNAL(finished()), &app, SLOT(quit())); // Invoke with Qt::QueuedConnection since the Qt event loop isn't up yet QMetaObject::invokeMethod(&database, "init", Qt::QueuedConnection); QMetaObject::invokeMethod(&sessionManager, "start", Qt::QueuedConnection); QMetaObject::invokeMethod(&game, "start", Qt::QueuedConnection); QMetaObject::invokeMethod(&udpServer, "start", Qt::QueuedConnection); // Run the primary thread's main event loop. // exec() will return when we stop the main event loop via a signal return app.exec(); }
bool KateApp::startupKate () { // user specified session to open if (m_args->isSet ("start")) { sessionManager()->activateSession (sessionManager()->giveSession (QString::fromLocal8Bit(m_args->getOption("start"))), false, false); } else { // let the user choose session if possible if (!sessionManager()->chooseSession ()) { // we will exit kate now, notify the rest of the world we are done KStartupInfo::appStarted (startupId()); return false; } } // oh, no mainwindow, create one, should not happen, but make sure ;) if (mainWindows() == 0) newMainWindow (); // notify about start KStartupInfo::setNewStartupId( activeMainWindow(), startupId()); QTextCodec *codec = m_args->isSet("encoding") ? QTextCodec::codecForName(m_args->getOption("encoding")) : 0; bool tempfileSet = KCmdLineArgs::isTempFileSet(); Kate::Document::setOpenErrorDialogsActivated (false); uint id = 0; for (int z=0; z<m_args->count(); z++) { // this file is no local dir, open it, else warn bool noDir = !m_args->url(z).isLocalFile() || !QDir (m_args->url(z).path()).exists(); if (noDir) { // open a normal file if (codec) id = activeMainWindow()->viewManager()->openURL( m_args->url(z), codec->name(), false, tempfileSet ); else id = activeMainWindow()->viewManager()->openURL( m_args->url(z), QString::null, false, tempfileSet ); } else KMessageBox::sorry( activeMainWindow(), i18n("The file '%1' could not be opened: it is not a normal file, it is a folder.").arg(m_args->url(z).url()) ); } Kate::Document::setOpenErrorDialogsActivated (true); // handle stdin input if( m_args->isSet( "stdin" ) ) { QTextIStream input(stdin); // set chosen codec if (codec) input.setCodec (codec); QString line; QString text; do { line = input.readLine(); text.append( line + "\n" ); } while( !line.isNull() ); openInput (text); } else if ( id ) activeMainWindow()->viewManager()->activateView( id ); if ( activeMainWindow()->viewManager()->viewCount () == 0 ) activeMainWindow()->viewManager()->activateView(m_docManager->firstDocument()->documentNumber()); int line = 0; int column = 0; bool nav = false; if (m_args->isSet ("line")) { line = m_args->getOption ("line").toInt(); nav = true; } if (m_args->isSet ("column")) { column = m_args->getOption ("column").toInt(); nav = true; } if (nav) activeMainWindow()->viewManager()->activeView ()->setCursorPosition (line, column); // show the nice tips KTipDialog::showTip(activeMainWindow()); return true; }