aboutsummaryrefslogtreecommitdiff
path: root/src-qt5/core/lumina-desktop/JsonMenu.h
blob: fbb80d28c38fac402188474d14b7d9b8d0e395d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//===========================================
//  Lumina Desktop source code
//  Copyright (c) 2016, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
//  This menu is used to automatically generate menu contents 
//    based on the JSON output of an external script/utility
//===========================================
#ifndef _LUMINA_DESKTOP_JSON_MENU_H
#define _LUMINA_DESKTOP_JSON_MENU_H

#include <QMenu>
#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

#include <LuminaUtils.h>
#include <LuminaXDG.h>

class JsonMenu : public QMenu{
	Q_OBJECT
private:
	QString exec;

public:
	JsonMenu(QString execpath, QWidget *parent = 0) : QMenu(parent){
	  exec = execpath;
	  connect(this, SIGNAL(aboutToShow()), this, SLOT(updateMenu()) );
	}

private slots:
	void parseObject(QString label, QJsonObject obj){
	  if( label.isEmpty() || !obj.contains("type") ){ return; }
          QString type = obj.value("type").toString();
	  if(type.toLower()=="item"){
	    QAction *act = this->addAction(label);
	    if(obj.contains("icon")){ act->setIcon( LXDG::findIcon(obj.value("icon").toString(),"") ); }
	    if(obj.contains("action")){ act->setWhatsThis( obj.value("action").toString() ); }
	    else{ act->setEnabled(false); } //not interactive
	  }else if(type.toLower()=="menu"){
	    
	  }else if(type.toLower()=="jsonmenu"){
	    //This is a recursive JSON menu object
	    if(!obj.contains("exec")){ return; }
	    JsonMenu *menu = new JsonMenu(obj.value("exec").toString(), this);
	      menu->setTitle(label);
	      if(obj.contains("icon")){ menu->setIcon(LXDG::findIcon(obj.value("icon").toString(),"") ); }
	    this->addMenu(menu);
	  }
	}
	void updateMenu(){
          this->clear();
	  QJsonDocument doc = QJsonDocument::fromJson( LUtils::getCmdOutput(exec).join(" ").toLocal8Bit() );
          if(doc.isNull() || !doc.isObject()){
	    this->addAction( QString(tr("Error parsing script output: %1")).arg("\n"+exec) )->setEnabled(false);
	  }else{
	    QStringList keys = doc.object().keys();
	    for(int i=0; i<keys.length(); i++){
	      if(doc.object().value(keys[i]).isObject()){
	        parseObject(keys[i], doc.object().value(keys[i]).toObject());
	      }
	    }
	  }
	}
};
#endif
bgstack15