Exemplo n.º 1
0
void killswitchEnabled(char nomTeamCourt[5])
{
    //Cette fonction est appelé si le killswitch est activé, elle recoit un nom de team, cherche ses mangas dans mangas et fais le ménage
    int i = 1;
    char temp[TAILLE_BUFFER], buffer[TAILLE_BUFFER];
    FILE *mangas = fopenR("mangas", "r");
    FILE *test = NULL;

    if(mangas != NULL)
    {
        while(i)
        {
            fscanf(mangas, "%s %s", buffer, temp);
            if(strcmp(temp, nomTeamCourt))
                while(fgetc(mangas) != '#');
            else
                i = 0;
        }
        crashTemp(temp, TAILLE_BUFFER);
        while(fgetc(mangas)!= '#')
        {
            fseek(mangas, -1, SEEK_CUR);
            fscanf(mangas, "%s %s %d %d %d %d\n", temp, buffer, &i, &i, &i, &i); //Seul temp est utilisé
            crashTemp(buffer, TAILLE_BUFFER);
            sprintf(buffer, "manga/%s/config.dat", temp);
            test = fopenR("buffer", "r");
            if(test != NULL)
            {
                fclose(test);
                crashTemp(buffer, TAILLE_BUFFER);
                sprintf(buffer, "manga/%s", temp);
                removeFolder(buffer, TAILLE_BUFFER);
            }
        }
    }
    fclose(mangas);
}
Exemplo n.º 2
0
void chanFileSystemDockWidget::createContextMenu() {

    m_actionArray[CreateFile]->setText("new file");
    connect(m_actionArray[CreateFile], SIGNAL(triggered()),
            this, SLOT(createFile()));

    m_actionArray[CreateFolder]->setText("new folder");
    connect(m_actionArray[CreateFolder], SIGNAL(triggered()),
            this, SLOT(createFolder()));

    m_actionArray[ImportFile]->setText("import file");
    connect(m_actionArray[ImportFile], SIGNAL(triggered()),
            this, SLOT(importFile()));

    m_actionArray[RemoveFile]->setText("remove file");
    connect(m_actionArray[RemoveFile], SIGNAL(triggered()),
            this, SLOT(removeFile()));

    m_actionArray[RemoveFolder]->setText("remove folder");
    connect(m_actionArray[RemoveFolder], SIGNAL(triggered()),
            this, SLOT(removeFolder()));

    m_actionArray[RenameFile]->setText("rename file");
    connect(m_actionArray[RenameFile], SIGNAL(triggered()),
            this, SLOT(renameFile()));

    m_actionArray[RenameFolder]->setText("rename folder");
    connect(m_actionArray[RenameFolder], SIGNAL(triggered()),
            this, SLOT(renameFolder()));

    std::for_each(m_actionArray, m_actionArray + actionArraySize, [this](QAction* item) {
        this->addAction(item);
    });

    setContextMenuPolicy(Qt::ContextMenuPolicy::ActionsContextMenu);
}
Exemplo n.º 3
0
FileSystemWidget::FileSystemWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent),
    m_liteApp(app)
{
    m_tree = new SymbolTreeView;
    m_tree->setHeaderHidden(true);
    m_model = new FileSystemModel(this);
    m_tree->setContextMenuPolicy(Qt::CustomContextMenu);
    m_tree->setModel(m_model);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin(0);
    layout->addWidget(m_tree);
    this->setLayout(layout);

    connect(m_tree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openPathIndex(QModelIndex)));
    connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*)));

    m_fileMenu = new QMenu(this);
    m_folderMenu = new QMenu(this);

    m_openEditorAct = new QAction(tr("Open Editor"),this);
    m_newFileAct = new QAction(tr("New File"),this);
    m_newFileWizardAct = new QAction(tr("New File Wizard"),this);
    m_renameFileAct = new QAction(tr("Rename File"),this);
    m_removeFileAct = new QAction(tr("Remove File"),this);

    m_newFolderAct = new QAction(tr("New Folder"),this);
    m_renameFolderAct = new QAction(tr("Rename Folder"),this);
    m_removeFolderAct = new QAction(tr("Remove Folder"),this);

    m_openShellAct = new QAction(tr("Open Terminal Here"),this);
    m_openExplorerAct = new QAction(tr("Open Explorer Here"),this);

    m_fileMenu->addAction(m_openEditorAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_newFileAct);
    m_fileMenu->addAction(m_newFileWizardAct);
    m_fileMenu->addAction(m_renameFileAct);
    m_fileMenu->addAction(m_removeFileAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openShellAct);
    m_fileMenu->addAction(m_openExplorerAct);

    m_folderMenu->addAction(m_newFileAct);
    m_folderMenu->addAction(m_newFileWizardAct);
    m_folderMenu->addAction(m_newFolderAct);
    m_folderMenu->addAction(m_renameFolderAct);
    m_folderMenu->addAction(m_removeFolderAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_openShellAct);
    m_folderMenu->addAction(m_openExplorerAct);


    connect(m_model->fileWatcher(),SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString)));
    connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor()));
    connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile()));
    connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard()));
    connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile()));
    connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile()));
    connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder()));
    connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder()));
    connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder()));
    connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell()));
    connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer()));

    connect(m_tree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint)));
}
Exemplo n.º 4
0
int main(int argc, char * argv[]) {
	if (argc < 2) {
		printf("You should provide at least the name of the input image!\n");
		return -1;
	}
	Choice processingType;
	switch (argc) {
		case 2:
			processingType = FREEIMAGE;
			printf("Applying FREEIMAGE...\n");
			break;
		case 3:
			processingType = PITIE;
			printf("Applying PITIE...\n");
			break;
		case 4:
			processingType = PITIE;
			printf("Applying PITIE...\n");
			break;
		case 5:
			processingType = GOOCH;
			printf("Applying GOOCH...\n");
			break;
		default:
			processingType = NONE;
			printf("Do not know what processing to apply !\n");
			return -1;
	}

	//Buffer for the new file names
	char strNewFileName[0x100];
	//Load and verify that input image is a True-Color one
	KImage *pImage = new KImage(argv[1]);
	if (pImage == NULL || !pImage->IsValid() || pImage->GetBPP() != 24) {
		printf("File %s does is not a valid True-Color image.\n", argv[1]);
		return -2;
	}
	if (processingType == GOOCH) {
		Color2Gray * clr2Gray = new Color2Gray(pImage);
		if (!clr2Gray) {
			printf("Could not allocate class Color2Gray. \n");
			return -1;
		}
		char buffer[1000];
		memset(buffer, 0, 1000);
		char * charpointer = new char[1000];

		convertToChar(argv[2], &charpointer);
		strcat(buffer, charpointer);
		strcat(buffer, " ");

		convertToChar(argv[3], &charpointer);
		strcat(buffer, charpointer);
		strcat(buffer, " ");

		convertToChar(argv[4], &charpointer);
		strcat(buffer, charpointer);

		//convert image with GOOCH algorithm

		KImage *pImageColor2Gray = clr2Gray->localC2G(buffer);
		sprintf(strNewFileName, "%s_GoochGray_%s_%s_%s.png", argv[1],
			argv[2], argv[3], argv[4]);
		pImageColor2Gray->SaveAs(strNewFileName, SAVE_PNG_DEFAULT);

		//convert image with BASIC algorithm
		KImage *pImageBasicGray = clr2Gray->localC2G(buffer,
			Color2Gray::BASIC_GREY);
		sprintf(strNewFileName, "%s_BasicGray.png", argv[1]);
		pImageBasicGray->SaveAs(strNewFileName, SAVE_PNG_DEFAULT);
	} else if (processingType == PITIE) {
		KImage *paletteImage = new KImage(argv[2]);
		if (paletteImage == NULL || !paletteImage->IsValid() ||
			paletteImage->GetBPP() != 24) {
			printf("Cannot perform Color Grading. \n");
			printf("File %s is not a valid True-Color image.",
				argv[2]);
			return -2;
		}
		ColorTransfer * Pitie = NULL;
		if (argc == 4) {
			char * pEnd = NULL;
			long int iterations = strtol(argv[3], &pEnd, 10);
			if (iterations == 0L) {
				printf("Invalid third argument for Pitie Color Grading.\n");
				printf("Provide a valid iterations number or accept the default value 10.\n");
				return -2;
			}
			Pitie = new ColorTransfer(pImage, paletteImage, iterations);
		} else {
			Pitie = new ColorTransfer(pImage, paletteImage);
		}
		assert(Pitie);
		KImage * recoloredImage = Pitie->applyRecoloring();
		assert(recoloredImage);
		removeExtension(argv[1]);
		argv[2] = removeFolder(argv[2]);
		removeExtension(argv[2]);
		sprintf(strNewFileName, "%s%s_Pitie.png", argv[1], argv[2]);
		printf("Result image saved to: %s\n", strNewFileName);
		recoloredImage->SaveAs(strNewFileName, SAVE_PNG_DEFAULT);
	} else if (processingType == FREEIMAGE) {
		//Convert to grayscale and then BlackAndWhite
		KImage *pImageGrayscale = pImage->ConvertToGrayscale();
		//Don't forget to delete the original, now useless image
		delete pImage;

		//Verify conversion success...
		if (pImageGrayscale == NULL || !pImageGrayscale->IsValid() || pImageGrayscale->GetBPP() != 8) {
			printf("Conversion to grayscale was not successful!");
			return -3;
		}
		//... and save grayscale image
		sprintf(strNewFileName, "%s_grayscale.TIF", argv[1]);
		pImageGrayscale->SaveAs(strNewFileName, SAVE_TIFF_LZW);
		//Request direct access to image pixels in raw format
		BYTE **pDataMatrixGrayscale = NULL;
		if (pImageGrayscale->BeginDirectAccess() &&
			(pDataMatrixGrayscale = pImageGrayscale->GetDataMatrix())
			!= NULL) {
			//If direct access is obtained get image attributes and
			//start processing pixels
			int intWidth = pImageGrayscale->GetWidth();
			int intHeight = pImageGrayscale->GetHeight();

			//Create binary image
			KImage *pImageBinary = new KImage(intWidth, intHeight, 1);
			if (pImageBinary->BeginDirectAccess()) {
				//Apply a threshold at half the grayscale range (0x00 is Full-Black, 0xFF is Full-White, 0x80 is the Middle-Gray)
				for (int y = intHeight - 1; y >= 0; y--)
					for (int x = intWidth - 1; x >= 0; x--) {
						//You may use this instead of the line below:
						//    BYTE PixelAtXY = pImageGrayscale->Get8BPPPixel(x, y)
						BYTE &PixelAtXY = pDataMatrixGrayscale[y][x];
						if (PixelAtXY < 0x80)
							//...if closer to black, set to black
							pImageBinary->Put1BPPPixel(x, y, false);
						else
							//...if closer to white, set to white
							pImageBinary->Put1BPPPixel(x, y, true);
					}

				//Close direct access
				pImageBinary->EndDirectAccess();

				//Save binarized image
				sprintf(strNewFileName, "%s_Black_and_White.TIF", argv[1]);
				pImageBinary->SaveAs(strNewFileName, SAVE_TIFF_CCITTFAX4);

				//Don't forget to delete the binary image
				delete pImageBinary;
			} else {
				printf("Unable to obtain direct access in binary image!");
				return -3;
			}

			//Close direct access
			pImageGrayscale->EndDirectAccess();
			delete pImageGrayscale;
		} else {
			printf("Unable to obtain direct access in grayscale image!");
			return -4;
		}
	}

	//Return with success
	return 0;
}
Exemplo n.º 5
0
 //Для папок делаем рекурсивный вызов  
 foreach (QString entry, lstDirs)
 {
  QString entryAbsPath = dir.absolutePath() + "/" + entry;
  QDir dr(entryAbsPath);
  removeFolder(dr);
 }
Exemplo n.º 6
0
FileBrowser::FileBrowser(LiteApi::IApplication *app, QObject *parent) :
    QObject(parent),
    m_liteApp(app)
{
    m_widget = new QWidget;
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);

    m_fileModel = new QFileSystemModel(this);
    m_fileModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);

    m_proxyModel = new QSortFileSystemProxyModel(this);
    m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    m_proxyModel->setDynamicSortFilter(true);
    m_proxyModel->setSourceModel(m_fileModel);
    m_proxyModel->sort(0);

    //create filter toolbar
    m_filterToolBar = new QToolBar(m_widget);
    m_filterToolBar->setIconSize(QSize(16,16));

    m_syncAct = new QAction(QIcon("icon:filebrowser/images/sync.png"),tr("Synchronize with editor"),this);
    m_syncAct->setCheckable(true);

    m_filterCombo = new QComboBox;
    m_filterCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
    m_filterCombo->setEditable(true);
    m_filterCombo->addItem("*");
    m_filterCombo->addItem("Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.e64;*.pro");
    m_filterCombo->addItem("*.sh;Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.*.c;*.cpp;*.h;*.hpp;*.e64;*.pro");

    m_filterToolBar->addAction(m_syncAct);
    m_filterToolBar->addSeparator();
    m_filterToolBar->addWidget(m_filterCombo);

    //create root toolbar
    m_rootToolBar = new QToolBar(m_widget);
    m_rootToolBar->setIconSize(QSize(16,16));

    m_cdupAct = new QAction(QIcon("icon:filebrowser/images/cdup.png"),tr("Open Parent"),this);

    m_rootCombo = new QComboBox;
    m_rootCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    m_rootCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
    m_rootCombo->setEditable(false);
    m_rootCombo->addItem(m_fileModel->myComputer().toString());

    m_rootToolBar->addAction(m_cdupAct);
    m_rootToolBar->addSeparator();
    m_rootToolBar->addWidget(m_rootCombo);

    //create treeview
    m_treeView = new QTreeView;
    m_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_treeView->setModel(m_proxyModel);

    m_treeView->setRootIsDecorated(true);
    m_treeView->setUniformRowHeights(true);
    m_treeView->setTextElideMode(Qt::ElideNone);
    m_treeView->setAttribute(Qt::WA_MacShowFocusRect, false);

    m_treeView->setHeaderHidden(true);
    m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // show horizontal scrollbar
#if QT_VERSION >= 0x050000
    m_treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_treeView->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_treeView->header()->setStretchLastSection(false);
    //hide
    int count = m_treeView->header()->count();
    for (int i = 1; i < count; i++) {
        m_treeView->setColumnHidden(i,true);
    }

    mainLayout->addWidget(m_filterToolBar);
    mainLayout->addWidget(m_rootToolBar);
    mainLayout->addWidget(m_treeView);
    m_widget->setLayout(mainLayout);

    //create menu
    m_fileMenu = new QMenu;
    m_folderMenu = new QMenu;
    m_rootMenu = new QMenu;

    m_openFileAct = new QAction(tr("Open File"),this);
    //m_openEditorAct = new QAction(tr("Open Editor"),this);
    m_newFileAct = new QAction(tr("New File..."),this);
    m_newFileWizardAct = new QAction(tr("New File Wizard..."),this);
    m_renameFileAct = new QAction(tr("Rename File..."),this);
    m_removeFileAct = new QAction(tr("Delete File"),this);

    m_setRootAct = new QAction(tr("Set As Root Folder"),this);
    m_newFolderAct = new QAction(tr("New Folder..."),this);
    m_renameFolderAct = new QAction(tr("Rename Folder..."),this);
    m_removeFolderAct = new QAction(tr("Delete Folder"),this);

    m_openShellAct = new QAction(tr("Open Terminal Here"),this);
    m_openExplorerAct = new QAction(tr("Open Explorer Here"),this);

    m_viewGodocAct = new QAction(tr("View Godoc Here"),this);

    m_loadFolderAct = new QAction(tr("Load Folder Project"),this);

    m_fileMenu->addAction(m_openFileAct);
    //m_fileMenu->addAction(m_openEditorAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_newFileAct);
    m_fileMenu->addAction(m_newFileWizardAct);
    m_fileMenu->addAction(m_renameFileAct);
    m_fileMenu->addAction(m_removeFileAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_loadFolderAct);
    m_fileMenu->addAction(m_viewGodocAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openShellAct);
    m_fileMenu->addAction(m_openExplorerAct);

    m_folderMenu->addAction(m_setRootAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_newFileAct);
    m_folderMenu->addAction(m_newFileWizardAct);
    m_folderMenu->addAction(m_newFolderAct);
    m_folderMenu->addAction(m_renameFolderAct);
    m_folderMenu->addAction(m_removeFolderAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_loadFolderAct);
    m_folderMenu->addAction(m_viewGodocAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_openShellAct);
    m_folderMenu->addAction(m_openExplorerAct);

    m_rootMenu->addAction(m_cdupAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_newFileAct);
    m_rootMenu->addAction(m_newFileWizardAct);
    m_rootMenu->addAction(m_newFolderAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_loadFolderAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_openShellAct);
    m_rootMenu->addAction(m_openExplorerAct);

    connect(m_openFileAct,SIGNAL(triggered()),this,SLOT(openFile()));
    //connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor()));    
    connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile()));
    connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard()));
    connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile()));
    connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile()));
    connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder()));
    connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder()));
    connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder()));
    connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell()));
    connect(m_setRootAct,SIGNAL(triggered()),this,SLOT(setFolderToRoot()));
    connect(m_cdupAct,SIGNAL(triggered()),this,SLOT(cdUp()));
    connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer()));
    connect(m_viewGodocAct,SIGNAL(triggered()),this,SLOT(viewGodoc()));
    connect(m_loadFolderAct,SIGNAL(triggered()),this,SLOT(loadFolderProject()));

    //QDockWidget *dock = m_liteApp->dockManager()->addDock(m_widget,tr("File Browser"));
    //connect(dock,SIGNAL(visibilityChanged(bool)),this,SLOT(visibilityChanged(bool)));
    m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_widget,"filesystem",tr("File System"),true);
    connect(m_toolWindowAct,SIGNAL(toggled(bool)),this,SLOT(visibilityChanged(bool)));
    connect(m_treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedTreeView(QModelIndex)));
    connect(m_filterCombo,SIGNAL(activated(QString)),this,SLOT(activatedFilter(QString)));
    connect(m_rootCombo,SIGNAL(activated(QString)),this,SLOT(activatedRoot(QString)));
    connect(m_syncAct,SIGNAL(triggered(bool)),this,SLOT(syncFileModel(bool)));
    connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*)));
    connect(m_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint)));

    QString root = m_liteApp->settings()->value("FileBrowser/root",m_fileModel->myComputer().toString()).toString();
    addFolderToRoot(root);
    bool b = m_liteApp->settings()->value("FileBrowser/synceditor",true).toBool();
    if (b) {
        m_syncAct->setChecked(true);
    }
}
Exemplo n.º 7
0
void Folder::removeFolder(Folder *folder)
{
    removeFolder(folder->getID());
}
Exemplo n.º 8
0
FileSystemWidget::FileSystemWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent),
    m_liteApp(app)
{
    m_tree = new SymbolTreeView;
    m_tree->setHeaderHidden(true);

#if QT_VERSION >= 0x050000
    m_tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_tree->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_tree->header()->setStretchLastSection(false);

    m_model = new FileSystemModel(this);

    QDir::Filters filters = QDir::AllDirs | QDir::Files | QDir::Drives
                            | QDir::Readable| QDir::Writable
                            | QDir::Executable/* | QDir::Hidden*/
                            | QDir::NoDotAndDotDot;
#ifdef Q_OS_WIN // Symlinked directories can cause file watcher warnings on Win32.
    filters |= QDir::NoSymLinks;
#endif
    m_model->setFilter(filters);

    m_tree->setContextMenuPolicy(Qt::CustomContextMenu);
    m_tree->setModel(m_model);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin(0);
    layout->addWidget(m_tree);
    this->setLayout(layout);

    connect(m_tree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openPathIndex(QModelIndex)));
    connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*)));

    m_fileMenu = new QMenu(this);
    m_folderMenu = new QMenu(this);
    m_rootMenu = new QMenu(this);

    m_openEditorAct = new QAction(tr("Open File"),this);
    m_newFileAct = new QAction(tr("New File..."),this);
    m_newFileWizardAct = new QAction(tr("New File Wizard..."),this);
    m_renameFileAct = new QAction(tr("Rename File..."),this);
    m_removeFileAct = new QAction(tr("Delete File"),this);

    m_newFolderAct = new QAction(tr("New Folder..."),this);
    m_renameFolderAct = new QAction(tr("Rename Folder..."),this);
    m_removeFolderAct = new QAction(tr("Delete Folder"),this);

    m_openShellAct = new QAction(tr("Open Terminal Here"),this);
    m_openExplorerAct = new QAction(tr("Open Explorer Here"),this);

    m_viewGodocAct = new QAction(tr("View Godoc Here"),this);

    m_addFolderAct = new QAction(tr("Add Folder..."),this);
    m_closeFolerAct = new QAction(tr("Close Folder"),this);

    m_closeAllFoldersAct = new QAction(tr("Close All Folders"),this);

    m_fileMenu->addAction(m_openEditorAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_newFileAct);
    m_fileMenu->addAction(m_newFileWizardAct);
    m_fileMenu->addAction(m_renameFileAct);
    m_fileMenu->addAction(m_removeFileAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_viewGodocAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openShellAct);
    m_fileMenu->addAction(m_openExplorerAct);

    m_folderMenu->addAction(m_newFileAct);
    m_folderMenu->addAction(m_newFileWizardAct);
    m_folderMenu->addAction(m_newFolderAct);
    m_folderMenu->addAction(m_renameFolderAct);
    m_folderMenu->addAction(m_removeFolderAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_closeFolerAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_viewGodocAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_openShellAct);
    m_folderMenu->addAction(m_openExplorerAct);

    m_rootMenu->addAction(m_addFolderAct);
    m_rootMenu->addSeparator();
    //m_rootMenu->addAction(m_closeAllFoldersAct);

    connect(m_model->fileWatcher(),SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString)));
    connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor()));
    connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile()));
    connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard()));
    connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile()));
    connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile()));
    connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder()));
    connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder()));
    connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder()));
    connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell()));
    connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer()));
    connect(m_viewGodocAct,SIGNAL(triggered()),this,SLOT(viewGodoc()));
    connect(m_addFolderAct,SIGNAL(triggered()),this,SLOT(addFolder()));
    connect(m_closeFolerAct,SIGNAL(triggered()),this,SLOT(closeFolder()));
    connect(m_closeAllFoldersAct,SIGNAL(triggered()),this,SLOT(closeAllFolders()));

    connect(m_tree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint)));
}
Exemplo n.º 9
0
GopathBrowser::GopathBrowser(LiteApi::IApplication *app, QObject *parent) :
    QObject(parent),
    m_liteApp(app)
{
    m_widget = new QWidget;

    m_toolBar = new QToolBar;
    m_toolBar->setIconSize(QSize(16,16));

    m_syncEditor = new QAction(QIcon(":/images/synceditor.png"),tr("Sync Editor"),this);
    m_syncEditor->setCheckable(true);
    m_syncProject = new QAction(QIcon(":/images/syncproject.png"),tr("Sync Project"),this);
    m_syncProject->setCheckable(true);

    m_startPathLabel = new QLabel;

    m_toolBar->addAction(m_syncEditor);
    m_toolBar->addAction(m_syncProject);
    m_toolBar->addSeparator();
    m_toolBar->addWidget(m_startPathLabel);

    m_pathTree = new QTreeView;
    m_pathTree->setHeaderHidden(true);
    m_model = new GopathModel(this);
    m_pathTree->setContextMenuPolicy(Qt::CustomContextMenu);
    m_pathTree->setModel(m_model);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin(0);
    layout->addWidget(m_toolBar);
    layout->addWidget(m_pathTree);
    m_widget->setLayout(layout);

    m_pathList = m_liteApp->settings()->value("golangtool/gopath").toStringList();

    //connect(m_pathTree->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(pathIndexChanged(QModelIndex)));
    connect(m_pathTree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openPathIndex(QModelIndex)));
    LiteApi::IEnvManager* envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager");
    connect(envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(reloadEnv()));
    connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*)));

    m_fileMenu = new QMenu(m_widget);
    m_folderMenu = new QMenu(m_widget);

    m_setStartAct = new QAction(tr("Set Activate Project"),this);
    m_openEditorAct = new QAction(tr("Open Editor"),this);
    m_newFileAct = new QAction(tr("New File"),this);
    m_newFileWizardAct = new QAction(tr("New File Wizard"),this);
    m_renameFileAct = new QAction(tr("Rename File"),this);
    m_removeFileAct = new QAction(tr("Remove File"),this);

    m_newFolderAct = new QAction(tr("New Folder"),this);
    m_renameFolderAct = new QAction(tr("Rename Folder"),this);
    m_removeFolderAct = new QAction(tr("Remove Folder"),this);

    m_openShellAct = new QAction(tr("Open Terminal Here"),this);
    m_openExplorerAct = new QAction(tr("Open Explorer Here"),this);

    m_fileMenu->addAction(m_openEditorAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_newFileAct);
    m_fileMenu->addAction(m_newFileWizardAct);
    m_fileMenu->addAction(m_renameFileAct);
    m_fileMenu->addAction(m_removeFileAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openShellAct);
    m_fileMenu->addAction(m_openExplorerAct);

    m_folderMenu->addAction(m_setStartAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_newFileAct);
    m_folderMenu->addAction(m_newFileWizardAct);
    m_folderMenu->addAction(m_newFolderAct);
    m_folderMenu->addAction(m_renameFolderAct);
    m_folderMenu->addAction(m_removeFolderAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_openShellAct);
    m_folderMenu->addAction(m_openExplorerAct);

    connect(m_startPathLabel,SIGNAL(linkActivated(QString)),this,SLOT(expandStartPath(QString)));
    connect(m_syncEditor,SIGNAL(triggered(bool)),this,SLOT(syncEditor(bool)));
    connect(m_syncProject,SIGNAL(triggered(bool)),this,SLOT(syncProject(bool)));
    connect(m_setStartAct,SIGNAL(triggered()),this,SLOT(setActivate()));
    connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor()));
    connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile()));
    connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard()));
    connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile()));
    connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile()));
    connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder()));
    connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder()));
    connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder()));
    connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell()));
    connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer()));

    connect(m_pathTree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint)));

    bool b = m_liteApp->settings()->value("GolangTool/synceditor",true).toBool();
    if (b) {
        m_syncEditor->toggle();
    }
    b = m_liteApp->settings()->value("GolangTool/syncproject",false).toBool();
    if (b) {
        m_syncProject->toggle();
    }
    m_startPathLabel->setText("null project");
}
Exemplo n.º 10
0
Arquivo: rm.c Projeto: mli9502/cs4513
// Write a function to recursively remove a folder.
// current path, dumpster path, flag to check wheter is the same partition.
// currPath and currDumpPath is changed every time removeFolder is called recursively.
void removeFolder(char* currPath, char* currDumpPath, int isSamePtn)
{
    DIR* dp;
    struct dirent* d;
    // printf("Directory is %s\n", currPath);
    // printf("Current dumpster path is %s\n", currDumpPath);
    // Update current dumpster path.
    char* newDumpPath;
    getDumpFilePath(currPath, currDumpPath, &newDumpPath);

    // printf("new dumpster path is %s\n", newDumpPath);

    // Get the mode for old folder.
    struct stat srcFolderStat;
    int sRtn = stat(currPath, &srcFolderStat);
    // If dRtn is not 0, stat() failed
    if(sRtn)
    {
        perror("stat() call failed");
        exit(sRtn);
    }

    // Create a new folder in dumpster and update currDumpPath.
    int mRtn = mkdir(newDumpPath, srcFolderStat.st_mode);
    if(mRtn)
    {
        perror("mkdir() call failed");
        exit(mRtn);
    }

    dp = opendir(currPath);
    if(dp == NULL)
    {
        perror("open() call failed");
        exit(-1);
    }
    d = readdir(dp);
    while(d)
    {
        if((strcmp(d->d_name, "..") == 0) ||
            (strcmp(d->d_name, ".") == 0))
        {
            // printf("Handling .. and . folder\n");
            d = readdir(dp);
            continue;
        }
        // Check wheter it is a folder or a file.
        struct stat currStat;
        // Get the current file.
        char* currFile = concat(currPath, "/");
        currFile = concat(currFile, d->d_name);
        // printf("Current processing file is: %s\n", currFile);
        int sRtn = stat(currFile, &currStat);
        if(sRtn)
        {
            perror("stat() call failed");
            exit(sRtn);
        }
        // If it is a file, remove file.
        if(S_ISREG(currStat.st_mode))
        {
            if(isSamePtn)
            {
                char* newPath;
                getDumpFilePath(currFile, newDumpPath, &newPath);
                int rRtn = rename(currFile, newPath);
                if(rRtn)
                {
                    perror("rename() call failed");
                    exit(rRtn);
                }
                int cRtn = chmod(newPath, currStat.st_mode);
                if(cRtn)
                {
                    perror("chmod() call failed");
                    exit(cRtn);
                }
            }
            else
            {
                copyToDump(currFile, newDumpPath, currStat);
                int uRtn = unlink(currFile);
                if(uRtn)
                {
                    perror("unlink() call failed");
                    exit(uRtn);
                }
            }
        } 
        else if(S_ISDIR(currStat.st_mode))
        {
            // If it is a directory.
            removeFolder(currFile, newDumpPath, isSamePtn);
            // printf("Before unlink folder\n");
            // printf("currFile is %s\n", currFile);
            int rRtn = rmdir(currFile);
            if(rRtn)
            {
                perror("unlink() call failed");
                exit(rRtn);
            }
        }
        free(currFile);
        d = readdir(dp); 
    }
    // Need to unlink dir!
    closedir(dp);
    // Set the time and mod for the new folder here.
    int cRtn = chmod(newDumpPath, srcFolderStat.st_mode);
    if(cRtn)
    {
        perror("chmod() call failed");
        exit(cRtn);
    }
    // const struct utimbuf srcTim = {srcFolderStat.st_atime, srcFolderStat.st_mtime};
    // int uRtn = utime(newDumpPath, &srcTim);
    // if(uRtn)
    // {
    //     perror("utime() call failed");
    //     exit(uRtn);
    // }
    free(newDumpPath);
}
Exemplo n.º 11
0
Arquivo: rm.c Projeto: mli9502/cs4513
int main(int argc, char** argv)
{
    int c;
    int i;
    extern int optind, opterr;
    opterr = 1;
    // Check the options.
    while((c = getopt(argc, argv, "fhr")) != -1)
    {
        switch(c)
        {
            case 'f':
            {
                // If -f is already presented.
                if(fFlg)
                {
                    errFlg ++;
                    break;
                }
                fFlg ++;
                break;
            }
            case 'h':
            {
                // If -h is already presented.
                if(hFlg)
                {
                    errFlg ++;
                    break;
                }
                hFlg ++;
                break;
            }
            case 'r':
            {
                // If -r is already presented.
                if(rFlg)
                {
                    errFlg ++;
                    break;
                }
                rFlg ++;
                break;
            }
            default:
            {
                errFlg ++;
            }
        }
    }
    if(errFlg)
    {
        usage();
        exit(-1);
    }
    // If -h is presented, display usage message.

    //TODO: Will the program terminate after displaying basic usage message ??

    if(hFlg)
    {
        usage();
    }
    // Get file names.
    int fileCnt = argc - optind;
    if(!fileCnt)
    {
        printf("rm: missing file name\n");
        exit(-1);
    }
    char* files[fileCnt];
    for(i = 0; i < fileCnt; i++)
    {
        files[i] = argv[i + optind];
    }

    // Get DUMPSTER environment variable.
    char* dumpPath = NULL;
    dumpPath = getenv("DUMPSTER");
    if(!dumpPath)
    {
        printf("No match for DUMPSTER in environment\n");
        exit(-1);
    }
    // printf("%s\n", dumpPath);
    // Get stat for dumpster.
    struct stat dumpStat;
    int dRtn = stat(dumpPath, &dumpStat);
    // If dRtn is not 0, stat() failed
    if(dRtn)
    {
        perror("stat() call failed");
        exit(dRtn);
    }
    // Move file to DUMPSTER
    for(i = 0; i < fileCnt; i ++)
    {
        char* file = files[i];
        // printf("Current processing file is: %s\n", file);
        // Check whether the file exists or not.
        // File not exist, report error and continue to next file.
        if(access(file, F_OK) == -1)
        {
            printf("File or folder %s does not exist\n", file);
            continue;
        }
        // Get stat for current file.
        struct stat fileStat;
        int fRtn = stat(file, &fileStat);
        if(fRtn)
        {
            perror("stat() call failed");
            exit(fRtn);
        }
        // TODO: Is -r need to be checked when -f is specified ? 
        if(fFlg)
        {
            if(S_ISREG(fileStat.st_mode))
            {
                int rRtn = remove(file);
                if(rRtn)
                {
                    perror("remove() call failed");
                    exit(rRtn);
                }
            }
            else if(S_ISDIR(fileStat.st_mode))
            {
                removeFolderForce(file);
                int rRtn = remove(file);
                if(rRtn)
                {
                    perror("remove() call failed");
                    exit(rRtn);
                }
            }
            continue;
        }

        // Check for partition.
        // Same partition.
        if(fileStat.st_dev == dumpStat.st_dev)
        {
            // printf("On same partition!\n");
            // Check for file or folder.
            // If it is a file, move it to the dumpster folder.
            if(S_ISREG(fileStat.st_mode))
            {
                char* newPath;
                // Get the file path in dumpster.
                getDumpFilePath(file, dumpPath, &newPath);
                int rRtn = rename(file, newPath);
                if(rRtn)
                {
                    perror("rename() call failed");
                    exit(rRtn);
                }
                int cRtn = chmod(newPath, fileStat.st_mode);
                if(cRtn)
                {
                    perror("chmod() call failed");
                    exit(cRtn);
                }

            }
            // If it is a folder.
            else if(S_ISDIR(fileStat.st_mode))
            {
                // Check for -r flag.
                // If -r is not presented on the folder. 
                if(!rFlg)
                {
                    printf("-r option missing for folder %s. ", file);
                    printf("Precede to the next file.\n");
                    continue;
                }
                // Remove the other files and folders in this folder.
                removeFolder(file, dumpPath, 1);
                // Remove this folder.
                int rRtn = rmdir(file);
                if(rRtn)
                {
                    perror("rmdir() call failed");
                    exit(rRtn);
                }
            }
        }
        else
        {
            // Check for file or folder.
            if(S_ISREG(fileStat.st_mode))
            {
                // printf("On different partition!\n");
                // Copy file and set metadata.
                copyToDump(file, dumpPath, fileStat);
                int uRtn = unlink(file);
                if(uRtn)
                {
                    perror("unlink() call failed");
                    exit(uRtn);
                }
            }
            else if(S_ISDIR(fileStat.st_mode))
            {
                if(!rFlg)
                {
                    printf("-r option missing for folder %s. ", file);
                    printf("Precede to the next file.\n");
                    continue;
                }
                removeFolder(file, dumpPath, 0);
                int rRtn = rmdir(file);
                if(rRtn)
                {
                    perror("rmdir() call failed");
                    exit(rRtn);
                }
            }
        }
    }
    return 0;
}
Exemplo n.º 12
0
bool MDLInstallation(void *buf, size_t sizeBuf, PROJECT_DATA *projectDB, uint chapitre, uint tome, bool subFolder, bool haveToPutTomeAsReadable)
{
    bool wentFine = true;
    char temp[600], basePath[500], *encodedPath = getPathForProject(*projectDB);
	
	if(encodedPath == NULL)
		return true;
	
    /*Récupération des valeurs envoyés*/
	
    if(tome != INVALID_VALUE)
    {
		if(subFolder)
		{
			if(chapitre % 10)
				snprintf(basePath, 500, PROJECT_ROOT"%s/"VOLUME_PREFIX"%u/"CHAPTER_PREFIX"%u.%u/", encodedPath, tome, chapitre / 10, chapitre % 10);
			else
				snprintf(basePath, 500, PROJECT_ROOT"%s/"VOLUME_PREFIX"%u/"CHAPTER_PREFIX"%u/", encodedPath, tome, chapitre / 10);
		}
		else
		{
			if(chapitre % 10)
				snprintf(basePath, 500, PROJECT_ROOT"%s/"VOLUME_PREFIX"%u/"VOLUME_PRESHARED_DIR"/"CHAPTER_PREFIX"%u.%u/", encodedPath, tome, chapitre / 10, chapitre % 10);
			else
				snprintf(basePath, 500, PROJECT_ROOT"%s/"VOLUME_PREFIX"%u/"VOLUME_PRESHARED_DIR"/"CHAPTER_PREFIX"%u/", encodedPath, tome, chapitre / 10);
		}
    }
    else
    {
        if(chapitre % 10)
            snprintf(basePath, 500, PROJECT_ROOT"%s/"CHAPTER_PREFIX"%u.%u/", encodedPath, chapitre / 10, chapitre % 10);
        else
            snprintf(basePath, 500, PROJECT_ROOT"%s/"CHAPTER_PREFIX"%u/", encodedPath, chapitre / 10);
    }
	
    snprintf(temp, 600, "%s/"CONFIGFILE, basePath);
    if(!checkFileExist(temp))
    {
		//Décompression dans le repertoire de destination
		
        mkdirR(basePath);
        if(!checkDirExist(basePath))
            createPath(basePath);
		
        //On crée un message pour ne pas lire un chapitre en cours d'install
        char installingFile[600];
        snprintf(installingFile, sizeof(installingFile), "%sinstalling", basePath);
        FILE* ressources = fopen(installingFile, "w+");

		if(ressources != NULL)
            fclose(ressources);
		
        wentFine &= decompressChapter(buf, sizeBuf, basePath, *projectDB, chapitre / 10);

		remove(installingFile);
		
		if(wentFine && haveToPutTomeAsReadable)
			setTomeReadable(*projectDB, tome);

		if(!subFolder && !wentFine)
		{
			logR("Archive Corrompue: %ls - %d - %d", projectDB->repo->name, projectDB->projectID, chapitre);
			removeFolder(basePath);
		}
    }

	if(wentFine)
	{
		//Add a flag signaling the file wasn't read yet
		if(tome != INVALID_VALUE)
			snprintf(basePath, 500, PROJECT_ROOT"%s/"VOLUME_PREFIX"%u/", encodedPath, tome);
		
		finishInstallationAtPath(basePath);
	}

	free(encodedPath);
    return wentFine;
}
Exemplo n.º 13
0
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation)
{
    QDir root(dest);
    if (!root.exists()) {
        QDir().mkpath(dest);
        if (!root.exists()) {
            d->errorMessage = i18n("Could not create package root directory: %1", dest);
            d->errorCode = Package::JobError::RootCreationError;
            //qWarning() << "Could not create package root directory: " << dest;
            return false;
        }
    }

    QFileInfo fileInfo(src);
    if (!fileInfo.exists()) {
        d->errorMessage = i18n("No such file: %1", src);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }

    QString path;
    QTemporaryDir tempdir;
    bool archivedPackage = false;

    if (fileInfo.isDir()) {
        // we have a directory, so let's just install what is in there
        path = src;
        // make sure we end in a slash!
        if (!path.endsWith('/')) {
            path.append('/');
        }
    } else {
        KArchive *archive = 0;
        QMimeDatabase db;
        QMimeType mimetype = db.mimeTypeForFile(src);
        if (mimetype.inherits(QStringLiteral("application/zip"))) {
            archive = new KZip(src);
        } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-xz")) ||
                   mimetype.inherits(QStringLiteral("application/x-lzma"))) {
            archive = new KTar(src);
        } else {
            //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name();
            d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name());
            d->errorCode = Package::JobError::UnsupportedArchiveFormatError;
            return false;
        }

        if (!archive->open(QIODevice::ReadOnly)) {
            //qWarning() << "Could not open package file:" << src;
            delete archive;
            d->errorMessage = i18n("Could not open package file: %1", src);
            d->errorCode = Package::JobError::PackageOpenError;
            return false;
        }

        archivedPackage = true;
        path = tempdir.path() + '/';

        d->installPath = path;

        const KArchiveDirectory *source = archive->directory();
        source->copyTo(path);

        QStringList entries = source->entries();
        if (entries.count() == 1) {
            const KArchiveEntry *entry = source->entry(entries[0]);
            if (entry->isDirectory()) {
                path.append(entry->name()).append("/");
            }
        }

        delete archive;
    }

    QDir packageDir(path);
    QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles);
    KPluginMetaData meta;
    if (!entries.isEmpty()) {
        const QString metadataFilePath = entries.first().filePath();
        if (metadataFilePath.endsWith(QLatin1String(".desktop")))
            meta = KPluginMetaData(metadataFilePath);
        else {
            QFile f(metadataFilePath);
            if(!f.open(QIODevice::ReadOnly)){
                qWarning() << "Couldn't open metadata file" << src << path;
                d->errorMessage = i18n("Could not open metadata file: %1", src);
                d->errorCode = Package::JobError::MetadataFileMissingError;
                return false;
            }
            QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object();
            meta = KPluginMetaData(metadataObject, QString(), metadataFilePath);
        }
    }

    if (!meta.isValid()) {
        qDebug() << "No metadata file in package" << src << path;
        d->errorMessage = i18n("No metadata file in package: %1", src);
        d->errorCode = Package::JobError::MetadataFileMissingError;
        return false;
    }


    QString pluginName = meta.pluginId();
    qDebug() << "pluginname: " << meta.pluginId();
    if (pluginName.isEmpty()) {
        //qWarning() << "Package plugin name not specified";
        d->errorMessage = i18n("Package plugin name not specified: %1", src);
        d->errorCode = Package::JobError::PluginNameMissingError;
        return false;
    }

    // Ensure that package names are safe so package uninstall can't inject
    // bad characters into the paths used for removal.
    QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period.
    if (!validatePluginName.exactMatch(pluginName)) {
        //qDebug() << "Package plugin name " << pluginName << "contains invalid characters";
        d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName);
        d->errorCode = Package::JobError::PluginNameInvalidError;
        return false;
    }

    QString targetName = dest;
    if (targetName[targetName.size() - 1] != '/') {
        targetName.append('/');
    }
    targetName.append(pluginName);

    if (QFile::exists(targetName)) {
        if (operation == Update) {
            KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop"));

            if (oldMeta.serviceTypes() != meta.serviceTypes()) {
                d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::UpdatePackageTypeMismatchError;
            } else if (isVersionNewer(oldMeta.version(), meta.version())) {
                const bool ok = uninstallPackage(targetName);
                if (!ok) {
                    d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage);
                    d->errorCode = Package::JobError::OldVersionRemovalError;
                }
            } else {
                d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError;
            }
        } else {
            d->errorMessage = i18n("%1 already exists", targetName);
            d->errorCode = Package::JobError::PackageAlreadyInstalledError;
        }

        if (d->errorCode != KJob::NoError) {
            d->installPath = targetName;
            return false;
        }
    }

    //install dependencies
    const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies"));
    for(const QString &dep : dependencies) {
        QUrl depUrl(dep);
        if (!installDependency(depUrl)) {
            d->errorMessage = i18n("Could not install dependency: %1", dep);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // it's in a temp dir, so just move it over.
        const bool ok = copyFolder(path, targetName);
        removeFolder(path);
        if (!ok) {
            //qWarning() << "Could not move package to destination:" << targetName;
            d->errorMessage = i18n("Could not move package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageMoveError;
            return false;
        }
    } else {
        // it's a directory containing the stuff, so copy the contents rather
        // than move them
        const bool ok = copyFolder(path, targetName);
        if (!ok) {
            //qWarning() << "Could not copy package to destination:" << targetName;
            d->errorMessage = i18n("Could not copy package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // no need to remove the temp dir (which has been successfully moved if it's an archive)
        tempdir.setAutoRemove(false);
    }


    indexDirectory(dest, QStringLiteral("kpluginindex.json"));


    d->installPath = targetName;

    //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed.";
    return true;
}
Exemplo n.º 14
0
Arquivo: dv.c Projeto: mli9502/cs4513
// currPath should be the file path in dumpster.
// destPath should be current working directory.
// file is the file name being transfered.
void removeFolder(char* currPath, char* file, int isSamePtn)
{
	DIR* dp;
	struct dirent* d;
	// printf("Directory is %s\n", currPath);
	char* tarPath = file;
	// printf("target path is %s\n", tarPath);
	struct stat srcFolderStat;
    int sRtn = stat(currPath, &srcFolderStat);
    // If dRtn is not 0, stat() failed
    if(sRtn)
    {
        perror("stat() call failed");
        exit(sRtn);
    }
    // Create a new folder in curretn working directory.
    int mRtn = mkdir(tarPath, srcFolderStat.st_mode);
    if(mRtn)
    {
        perror("mkdir() call failed");
        exit(mRtn);
    }
    // Open the directory in dumpster.
    dp = opendir(currPath);
    if(dp == NULL)
    {
        perror("open() call failed");
        exit(-1);
    }
    d = readdir(dp);
    while(d)
    {
    	if((strcmp(d->d_name, "..") == 0) ||
    		(strcmp(d->d_name, ".") == 0))
    	{
    		// printf("Handling .. and . folder\n");
    		d = readdir(dp);
    		continue;
    	}
    	struct stat currStat;
    	char* currFile = concat(currPath, "/");
    	currFile = concat(currFile, d->d_name);
    	// printf("Current processing file is: %s\n", currFile);
    	int sRtn = stat(currFile, &currStat);
    	if(sRtn)
    	{
    		perror("stat() call failed");
    		exit(sRtn);
    	}
    	char* newTarPath = concat(tarPath, "/");
    	newTarPath = concat(newTarPath, d->d_name);
    	if(S_ISREG(currStat.st_mode))
    	{
    		if(isSamePtn)
    		{
    			// printf("newTarPath is %s\n", newTarPath);
    			int rRtn = rename(currFile, newTarPath);
    			if(rRtn)
    			{
    				perror("rename() call failed");
    				exit(rRtn);
    			}
                int cRtn = chmod(newTarPath, currStat.st_mode);
                // printf("cRtn is %d\n", cRtn);
                if(cRtn)
                {
                    perror("chmod() call failed");
                    exit(cRtn);
                }
    		}
    		else
    		{
    			// Copy file to newTarPath.
    			copyToTar(currFile, newTarPath, currStat);
    			int uRtn = unlink(currFile);
				if(uRtn)
                {
                    perror("unlink() call failed");
                    exit(uRtn);
                }
    		}
    	}
    	else if(S_ISDIR(currStat.st_mode))
    	{
    		removeFolder(currFile, newTarPath, isSamePtn);
    		int rRtn = rmdir(currFile);
            if(rRtn)
            {
                perror("rmdir() call failed");
                exit(rRtn);
            }
    	}
    	free(currFile);
    	free(newTarPath);
        d = readdir(dp); 
    }
    closedir(dp);
    int cRtn = chmod(tarPath, srcFolderStat.st_mode);
    if(cRtn)
    {
        perror("chmod() call failed");
        exit(cRtn);
    }

}
Exemplo n.º 15
0
Arquivo: dv.c Projeto: mli9502/cs4513
int main(int argc, char** argv)
{
	int c, i;
	int hFlg = 0;
	int errFlg = 0;
	extern int optind, opterr;
	opterr = 1;
	while((c = getopt(argc, argv, "h")) != -1)
	{
		switch(c)
		{
			case 'h':
			{
				if(hFlg)
				{
					errFlg ++;
					break;
				}
				hFlg ++;
				break;
			}
			default:
			{
				errFlg ++;
			}
		}
	}
	if(errFlg)
	{
		usage();
		exit(-1);
	}
	if(hFlg)
	{
		usage();
	}
	// Get file names.
	int fileCnt = argc - optind;
	if(!fileCnt)
	{
		printf("dv: missing file name\n");
		exit(-1);
	}
	char* files[fileCnt];
	for(i = 0; i < fileCnt; i ++)
	{
		files[i] = argv[i + optind];
	}

	// Get DUMPSTER environment variable.
	char* dumpPath = NULL;
	dumpPath = getenv("DUMPSTER");
	if(!dumpPath)
	{
		printf("No match for DUMPSTER in environment\n");
		exit(-1);
	}
	// Get stat for dumpster.
	struct stat dumpStat;
	int sRtn = stat(dumpPath, &dumpStat);
	if(sRtn)
	{
		perror("stat() call failed");
		exit(sRtn);
	}
	// Get information for current directory.
	char currDir[1024];
	char* gRtn = getcwd(currDir, 1024);
	if(!gRtn)
	{
		perror("getcwd() call failed");
		exit(-1);
	}
	// printf("Current working directory is %s\n", currDir);
	// Get stat for current working directory.
	struct stat currDirStat;
	sRtn = stat(currDir, &currDirStat);
	if(sRtn)
	{
		perror("stat() call failed");
		exit(sRtn);
	}
	// Move file from dumpster to current directory.
	// Check for partition.
	// printf("On same partition\n");
	for(i = 0; i < fileCnt; i++)
	{
		char* file = files[i];
		// Check for file existance.
		int aRtn = access(file, F_OK);
		if(aRtn == 0)
		{
			printf("File or folder %s already exists in current directory!\n", file);
			exit(-1);
		}
		// Free this!
		// Get the file in dumpster.
		char* srcPath;
		getSrcFilePath(file, dumpPath, &srcPath);
		// TODO: May have to report error when input is "/..."
		// Get the file name of the actual file.
		char* dupFile = strdup(file);
		char* tarFile;
		char* token;
		while((token = strsep(&dupFile, "/"))){
			// printf("%s\n", token);
			tarFile = strdup(token);
		}
		// printf("Final token is %s\n", tarFile);
		// int k = 0;
		// for(k = 0; k < j; k ++){
		// 	printf("%s\n", tokens[j]);
		// }
		// Use access to check whether fiel exists.
		if(access(srcPath, F_OK) == -1){
			printf("File or folder %s does not exits\n", srcPath);
			continue;
		}
		struct stat srcFileStat;
		int sRtn = stat(srcPath, &srcFileStat);
		if(sRtn)
		{
			perror("stat() call failed");
			exit(sRtn);
		}
		// Check partition here!
		// Check file or folder.
		// If same partition.
		if(dumpStat.st_dev == currDirStat.st_dev)
		{
			// If it ia s file.
			if(S_ISREG(srcFileStat.st_mode))
			{
				// printf("It is a file!\n");
				int rRtn = rename(srcPath, tarFile);
                if(rRtn)
                {
                    perror("rename() call failed");
                    exit(rRtn);
                }
                int cRtn = chmod(tarFile, srcFileStat.st_mode);
                // printf("cRtn is %d\n", cRtn);
                if(cRtn)
                {
                    perror("chmod() call failed");
                    exit(cRtn);
                }
			}
			else if(S_ISDIR(srcFileStat.st_mode))
			{
				// Recursively add new folder back to current directory.
				removeFolder(srcPath, tarFile, 1);
				int rRtn = rmdir(srcPath);
                if(rRtn)
                {
                    perror("rmdir() call failed");
                    exit(rRtn);
                }
			}
		}
		else
		{
			if(S_ISREG(srcFileStat.st_mode))
			{
				copyToTar(srcPath, tarFile, srcFileStat);
				int uRtn = unlink(srcPath);
				if(uRtn)
                {
                    perror("unlink() call failed");
                    exit(uRtn);
                }
			}
			else if(S_ISDIR(srcFileStat.st_mode))
			{
				removeFolder(srcPath, tarFile, 0);
				int rRtn = rmdir(srcPath);
				if(rRtn)
				{
					perror("rmdir() call failed");
					exit(rRtn);
				}
			}
		}
		
	}

}
Exemplo n.º 16
0
bool CryptoDoc::decrypt()
{
	if( isNull() )
	{
		setLastError( tr("Container is not open") );
		return false;
	}
	if( !isEncrypted() )
		return true;

	DEncEncryptedKey *key = 0;
	for( int i = 0; i < m_enc->nEncryptedKeys; ++i )
	{
		DEncEncryptedKey *tmp = m_enc->arrEncryptedKeys[i];
		if( qApp->poller()->token().cert() == SslCertificate::fromX509( Qt::HANDLE(tmp->pCert) ) )
		{
			key = tmp;
			break;
		}
	}
	if( !key )
	{
		setLastError( tr("You do not have the key to decrypt this document") );
		return false;
	}

	QByteArray in( (const char*)key->mbufTransportKey.pMem, key->mbufTransportKey.nLen ), out;
	bool decrypted = false;
	while( !decrypted )
	{
		switch( qApp->poller()->decrypt( in, out ) )
		{
		case Poller::DecryptOK: decrypted = true; break;
		case Poller::PinIncorrect: break;
		default: return false;
		}
	}

	ddocMemAssignData( &m_enc->mbufTransportKey, out.constData(), out.size() );
	m_enc->nKeyStatus = DENC_KEY_STATUS_INITIALIZED;
	int err = dencEncryptedData_decryptData( m_enc );
	if( err != ERR_OK )
	{
		setLastError( tr("Failed decrypt data"), err );
		return false;
	}

	DEncEncryptionProperty *prop = dencEncryptedData_FindEncryptionPropertyByName( m_enc, ENCPROP_ORIG_SIZE );
	if( prop && prop->szContent )
	{
		long size = QByteArray( prop->szContent ).toLong();
		if( size > 0 && size < m_enc->mbufEncryptedData.nLen )
			m_enc->mbufEncryptedData.nLen = size;
	}

	QString docName = QFileInfo( m_fileName ).fileName();
	m_ddocTemp = Common::tempFilename();
	removeFolder( m_ddocTemp );
	QDir().mkdir( m_ddocTemp );

	m_ddoc = QString( "%1/%2.ddoc" ).arg( m_ddocTemp ).arg( docName );
	QFile f( m_ddoc );
	if( !f.open( QIODevice::WriteOnly|QIODevice::Truncate ) )
	{
		setLastError( tr("Failed to create temporary files<br />%1").arg( f.errorString() ) );
		return false;
	}
	f.write( (const char*)m_enc->mbufEncryptedData.pMem, m_enc->mbufEncryptedData.nLen );
	f.close();
	ddocMemBuf_free( &m_enc->mbufEncryptedData );

	err = ddocSaxReadSignedDocFromFile( &m_doc, f.fileName().toUtf8(), 0, 0 );
	if( err != ERR_OK )
	{
		setLastError( tr("Failed to read decrypted data"), err );
		return false;
	}

	for( int i = 0; i < m_doc->nDataFiles; ++i )
	{
		QString file = QString( "%1/%2" ).arg( m_ddocTemp )
			.arg( QString::fromUtf8( m_doc->pDataFiles[i]->szFileName ) );
		if( QFile::exists( file ) )
			QFile::remove( file );
		err = ddocSaxExtractDataFile( m_doc, m_ddoc.toUtf8(),
			file.toUtf8(), m_doc->pDataFiles[i]->szId, CHARSET_UTF_8 );
		if( err == ERR_OK )
		{
			ddocMemAssignString( &m_doc->pDataFiles[i]->szFileName, file.toUtf8() );
			QFile::setPermissions( file, QFile::ReadOwner );
		}
		else
			setLastError( tr("Failed to save file '%1'").arg( file ), err );
	}

	cleanProperties();
	return !isEncrypted();
}