<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LPlugins.h"

#include <LUtils.h>

LPlugins::LPlugins(){
  LoadPanelPlugins();
  LoadDesktopPlugins();
  LoadMenuPlugins();
  LoadColorItems();
}

LPlugins::~LPlugins(){
}

//Plugin lists
QStringList LPlugins::panelPlugins(){
  QStringList pan = PANEL.keys();
    pan.sort();
  return pan;
}
QStringList LPlugins::desktopPlugins(){
  QStringList desk = DESKTOP.keys();
	desk.sort();
  return desk;
}
QStringList LPlugins::menuPlugins(){
    QStringList men = MENU.keys();
	men.sort();
  return men;
}
QStringList LPlugins::colorItems(){
  return COLORS.keys();
}
//Information on individual plugins
LPI LPlugins::panelPluginInfo(QString plug){
  if(PANEL.contains(plug)){ return PANEL[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::desktopPluginInfo(QString plug){
  if(DESKTOP.contains(plug)){ return DESKTOP[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::menuPluginInfo(QString plug){
  if(MENU.contains(plug)){ return MENU[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::colorInfo(QString item){
  if(COLORS.contains(item)){ return COLORS[item]; }
  else{ return LPI(); }
}

//===================
//             PLUGINS
//===================
//   PANEL PLUGINS
void LPlugins::LoadPanelPlugins(){
  PANEL.clear();
  //User Button
  LPI info;
    info.name = QObject::tr("User Menu");
    info.description = QObject::tr("Start menu alternative focusing on the user's files, directories, and favorites.");
    info.ID = "userbutton";
    info.icon = "user-identity";
  PANEL.insert(info.ID, info);
   //Application Menu
  info = LPI(); //clear it
    info.name = QObject::tr("Application Menu");
    info.description = QObject::tr("Start menu alternative which focuses on launching applications.");
    info.ID = "appmenu";
    info.icon = "format-list-unordered";
  PANEL.insert(info.ID, info);
  //Desktop Bar
  info = LPI(); //clear it
    info.name = QObject::tr("Desktop Bar");
    info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.");
    info.ID = "desktopbar";
    info.icon = "user-desktop";
  PANEL.insert(info.ID, info);
  //Spacer
  info = LPI(); //clear it
    info.name = QObject::tr("Spacer");
    info.description = QObject::tr("Invisible spacer to separate plugins.");
    info.ID = "spacer";
    info.icon = "transform-move";
  PANEL.insert(info.ID, info);
  //Line
  info = LPI(); //clear it
    info.name = QObject::tr("Line");
    info.description = QObject::tr("Simple line to provide visual separation between items.");
    info.ID = "line";
    info.icon = "insert-horizontal-rule";
  PANEL.insert(info.ID, info);
  //Desktop Switcher
  info = LPI(); //clear it
    info.name = QObject::tr("Workspace Switcher");
    info.description = QObject::tr("Controls for switching between the various virtual desktops.");
    info.ID = "desktopswitcher";
    info.icon = "preferences-desktop-display-color";
  PANEL.insert(info.ID, info);
  //Battery
  info = LPI(); //clear it
    info.name = QObject::tr("Battery Monitor");
    info.description = QObject::tr("Keep track of your battery status.");
    info.ID = "battery";
    info.icon = "battery-charging";
  PANEL.insert(info.ID, info);
  //Clock
  info = LPI(); //clear it
    info.name = QObject::tr("Time/Date");
    info.description = QObject::tr("View the current time and date.");
    info.ID = "clock";
    info.icon = "preferences-system-time";
  PANEL.insert(info.ID, info);
  //System Dachboard plugin
  info = LPI(); //clear it
    info.name = QObject::tr("System Dashboard");
    info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops).");
    info.ID = "systemdashboard";
    info.icon = "dashboard-show";
  PANEL.insert(info.ID, info);
  //Task Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager");
    info.description = QObject::tr("View and control any running application windows (group similar windows under a single button).");
    info.ID = "taskmanager";
    info.icon = "preferences-system-windows";
  PANEL.insert(info.ID, info);
  //Task Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager (No Groups)");
    info.description = QObject::tr("View and control any running application windows (every individual window has a button)");
    info.ID = "taskmanager-nogroups";
    info.icon = "preferences-system-windows";
  PANEL.insert(info.ID, info);
  //System Tray
  info = LPI(); //clear it
    info.name = QObject::tr("System Tray");
    info.description = QObject::tr("Display area for dockable system applications");
    info.ID = "systemtray";
    info.icon = "preferences-system-windows-actions";
  PANEL.insert(info.ID, info);
  //Home Button
  info = LPI(); //clear it
    info.name = QObject::tr("Show Desktop");
    info.description = QObject::tr("Hide all open windows and show the desktop");
    info.ID = "homebutton";
    info.icon = "user-desktop";
  PANEL.insert(info.ID, info);
  //Start Menu
  info = LPI(); //clear it
    info.name = QObject::tr("Start Menu");
    info.description = QObject::tr("Unified system access and application launch menu.");
    info.ID = "systemstart";
    info.icon = "Lumina-DE";
  PANEL.insert(info.ID, info);
  //Application Launcher
  info = LPI(); //clear it
    info.name = QObject::tr("Application Launcher");
    info.description = QObject::tr("Pin an application shortcut directly to the panel");
    info.ID = "applauncher";
    info.icon = "quickopen";
  PANEL.insert(info.ID, info);
}

// DESKTOP PLUGINS
void LPlugins::LoadDesktopPlugins(){
  DESKTOP.clear();
  //Calendar Plugin
  LPI info;
    info.name = QObject::tr("Calendar");
    info.description = QObject::tr("Display a calendar on the desktop");
    info.ID = "calendar";
    info.icon = "view-calendar";
  DESKTOP.insert(info.ID, info);
  //Application Launcher Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Application Launcher");
    info.description = QObject::tr("Desktop button for launching an application");
    info.ID = "applauncher";
    info.icon = "quickopen";
  DESKTOP.insert(info.ID, info);
  //Desktop View Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Desktop Icons View");
    info.description = QObject::tr("Configurable area for automatically showing desktop icons");
    info.ID = "desktopview";
    info.icon = "preferences-desktop-icons";
  DESKTOP.insert(info.ID, info);
  //Notepad Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Note Pad");
    info.description = QObject::tr("Keep simple text notes on your desktop");
    info.ID = "notepad";
    info.icon = "text-enriched";
  DESKTOP.insert(info.ID, info);
  //Audio Player Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Audio Player");
    info.description = QObject::tr("Play through lists of audio files");
    info.ID = "audioplayer";
    info.icon = "media-playback-start";
  DESKTOP.insert(info.ID, info);
  //System Monitor Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("System Monitor");
    info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures.");
    info.ID = "systemmonitor";
    info.icon = "cpu";
  DESKTOP.insert(info.ID, info);
  //RSS Reader Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("RSS Reader");
    info.description = QObject::tr("Monitor RSS Feeds (Requires internet connection)");
    info.ID = "rssreader";
    info.icon = "application-rss+xml";
  DESKTOP.insert(info.ID, info);
  //Available QtQuick scripts
  /*QStringList quickID = LUtils::listQuickPlugins();
  for(int i=0; i<quickID.length(); i++){
    QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon]
    if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other)
    info = LPI();
      info.name = quickinfo[0];
      info.description = quickinfo[1];
      info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax
      info.icon = quickinfo[2];
    DESKTOP.insert(info.ID, info);
  }*/
}

//    MENU PLUGINS
void LPlugins::LoadMenuPlugins(){
  MENU.clear();
  //Terminal
  LPI info;
    info.name = QObject::tr("Terminal");
    info.description = QObject::tr("Start the default system terminal.");
    info.ID = "terminal";
    info.icon = "utilities-terminal";
  MENU.insert(info.ID, info);
  //File Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Browse Files");
    info.description = QObject::tr("Browse the system with the default file manager.");
    info.ID = "filemanager";
    info.icon = "Insight-FileManager";
  MENU.insert(info.ID, info);
  //Applications
  info = LPI(); //clear it
    info.name = QObject::tr("Applications");
    info.description = QObject::tr("Show the system applications menu.");
    info.ID = "applications";
    info.icon = "system-run";
  MENU.insert(info.ID, info);
  //Line seperator
  info = LPI(); //clear it
    info.name = QObject::tr("Separator");
    info.description = QObject::tr("Static horizontal line.");
    info.ID = "line";
    info.icon = "insert-horizontal-rule";
  MENU.insert(info.ID, info);
  //Settings
  info = LPI(); //clear it
    info.name = QObject::tr("Preferences");
    info.description = QObject::tr("Show the desktop settings menu.");
    info.ID = "settings";
    info.icon = "configure";
  MENU.insert(info.ID, info);
  //Window List
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager");
    info.description = QObject::tr("List the open, minimized, active, and urgent application windows");
    info.ID = "windowlist";
    info.icon = "preferences-system-windows";
  MENU.insert(info.ID, info);
  //Custom Apps
  info = LPI(); //clear it
    info.name = QObject::tr("Custom App");
    info.description = QObject::tr("Start a custom application");
    info.ID = "app";
    info.icon = "application-x-desktop";
  MENU.insert(info.ID, info);
  //Custom Apps
  info = LPI(); //clear it
    info.name = QObject::tr("Menu Script");
    info.description = QObject::tr("Run an external script to generate a user defined menu");
    info.ID = "jsonmenu";
    info.icon = "text-x-script";
  MENU.insert(info.ID, info);
}

void LPlugins::LoadColorItems(){
  COLORS.clear();
  //Text Color
  LPI info;
    info.name = QObject::tr("Text");
    info.description = QObject::tr("Color to use for all visible text.");
    info.ID = "TEXTCOLOR";
  COLORS.insert(info.ID, info);
  //Text Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Text (Disabled)");
    info.description = QObject::tr("Text color for disabled or inactive items.");
    info.ID = "TEXTDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Text Color (Highlighted)
  info = LPI(); //clear it
    info.name = QObject::tr("Text (Highlighted)");
    info.description = QObject::tr("Text color when selection is highlighted.");
    info.ID = "TEXTHIGHLIGHTCOLOR";
  COLORS.insert(info.ID, info);
  //Base Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Base Window Color");
    info.description = QObject::tr("Main background color for the window/dialog.");
    info.ID = "BASECOLOR";
  COLORS.insert(info.ID, info);
  //Base Color (Alternate)
  info = LPI(); //clear it
    info.name = QObject::tr("Base Window Color (Alternate)");
    info.description = QObject::tr("Main background color for widgets that list or display collections of items.");
    info.ID = "ALTBASECOLOR";
  COLORS.insert(info.ID, info);
  //Primary Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Primary Color");
    info.description = QObject::tr("Dominant color for the theme.");
    info.ID = "PRIMARYCOLOR";
  COLORS.insert(info.ID, info);
  //Primary Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Primary Color (Disabled)");
    info.description = QObject::tr("Dominant color for the theme (more subdued).");
    info.ID = "PRIMARYDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Secondary Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Secondary Color");
    info.description = QObject::tr("Alternate color for the theme.");
    info.ID = "SECONDARYCOLOR";
  COLORS.insert(info.ID, info);
  //Secondary Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Secondary Color (Disabled)");
    info.description = QObject::tr("Alternate color for the theme (more subdued).");
    info.ID = "SECONDARYDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Accent Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Accent Color");
    info.description = QObject::tr("Color used for borders or other accents.");
    info.ID = "ACCENTCOLOR";
  COLORS.insert(info.ID, info);
  //Accent Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Accent Color (Disabled)");
    info.description = QObject::tr("Color used for borders or other accents (more subdued).");
    info.ID = "ACCENTDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Highlight Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Highlight Color");
    info.description = QObject::tr("Color used for highlighting an item.");
    info.ID = "HIGHLIGHTCOLOR";
  COLORS.insert(info.ID, info);
  //Highlight Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Highlight Color (Disabled)");
    info.description = QObject::tr("Color used for highlighting an item (more subdued).");
    info.ID = "HIGHLIGHTDISABLECOLOR";
  COLORS.insert(info.ID, info);
}
<commit_msg>Make lumina-config aware of the new "audioplayer" panel plugin.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LPlugins.h"

#include <LUtils.h>

LPlugins::LPlugins(){
  LoadPanelPlugins();
  LoadDesktopPlugins();
  LoadMenuPlugins();
  LoadColorItems();
}

LPlugins::~LPlugins(){
}

//Plugin lists
QStringList LPlugins::panelPlugins(){
  QStringList pan = PANEL.keys();
    pan.sort();
  return pan;
}
QStringList LPlugins::desktopPlugins(){
  QStringList desk = DESKTOP.keys();
	desk.sort();
  return desk;
}
QStringList LPlugins::menuPlugins(){
    QStringList men = MENU.keys();
	men.sort();
  return men;
}
QStringList LPlugins::colorItems(){
  return COLORS.keys();
}
//Information on individual plugins
LPI LPlugins::panelPluginInfo(QString plug){
  if(PANEL.contains(plug)){ return PANEL[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::desktopPluginInfo(QString plug){
  if(DESKTOP.contains(plug)){ return DESKTOP[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::menuPluginInfo(QString plug){
  if(MENU.contains(plug)){ return MENU[plug]; }
  else{ return LPI(); }
}
LPI LPlugins::colorInfo(QString item){
  if(COLORS.contains(item)){ return COLORS[item]; }
  else{ return LPI(); }
}

//===================
//             PLUGINS
//===================
//   PANEL PLUGINS
void LPlugins::LoadPanelPlugins(){
  PANEL.clear();
  //User Button
  LPI info;
    info.name = QObject::tr("User Menu");
    info.description = QObject::tr("Start menu alternative focusing on the user's files, directories, and favorites.");
    info.ID = "userbutton";
    info.icon = "user-identity";
  PANEL.insert(info.ID, info);
   //Application Menu
  info = LPI(); //clear it
    info.name = QObject::tr("Application Menu");
    info.description = QObject::tr("Start menu alternative which focuses on launching applications.");
    info.ID = "appmenu";
    info.icon = "format-list-unordered";
  PANEL.insert(info.ID, info);
  //Desktop Bar
  info = LPI(); //clear it
    info.name = QObject::tr("Desktop Bar");
    info.description = QObject::tr("This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.");
    info.ID = "desktopbar";
    info.icon = "user-desktop";
  PANEL.insert(info.ID, info);
  //Spacer
  info = LPI(); //clear it
    info.name = QObject::tr("Spacer");
    info.description = QObject::tr("Invisible spacer to separate plugins.");
    info.ID = "spacer";
    info.icon = "transform-move";
  PANEL.insert(info.ID, info);
  //Line
  info = LPI(); //clear it
    info.name = QObject::tr("Line");
    info.description = QObject::tr("Simple line to provide visual separation between items.");
    info.ID = "line";
    info.icon = "insert-horizontal-rule";
  PANEL.insert(info.ID, info);
  //Desktop Switcher
  info = LPI(); //clear it
    info.name = QObject::tr("Workspace Switcher");
    info.description = QObject::tr("Controls for switching between the various virtual desktops.");
    info.ID = "desktopswitcher";
    info.icon = "preferences-desktop-display-color";
  PANEL.insert(info.ID, info);
  //Battery
  info = LPI(); //clear it
    info.name = QObject::tr("Battery Monitor");
    info.description = QObject::tr("Keep track of your battery status.");
    info.ID = "battery";
    info.icon = "battery-charging";
  PANEL.insert(info.ID, info);
  //Clock
  info = LPI(); //clear it
    info.name = QObject::tr("Time/Date");
    info.description = QObject::tr("View the current time and date.");
    info.ID = "clock";
    info.icon = "preferences-system-time";
  PANEL.insert(info.ID, info);
  //System Dachboard plugin
  info = LPI(); //clear it
    info.name = QObject::tr("System Dashboard");
    info.description = QObject::tr("View or change system settings (audio volume, screen brightness, battery life, virtual desktops).");
    info.ID = "systemdashboard";
    info.icon = "dashboard-show";
  PANEL.insert(info.ID, info);
  //Task Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager");
    info.description = QObject::tr("View and control any running application windows (group similar windows under a single button).");
    info.ID = "taskmanager";
    info.icon = "preferences-system-windows";
  PANEL.insert(info.ID, info);
  //Task Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager (No Groups)");
    info.description = QObject::tr("View and control any running application windows (every individual window has a button)");
    info.ID = "taskmanager-nogroups";
    info.icon = "preferences-system-windows";
  PANEL.insert(info.ID, info);
  //System Tray
  info = LPI(); //clear it
    info.name = QObject::tr("System Tray");
    info.description = QObject::tr("Display area for dockable system applications");
    info.ID = "systemtray";
    info.icon = "preferences-system-windows-actions";
  PANEL.insert(info.ID, info);
  //Home Button
  info = LPI(); //clear it
    info.name = QObject::tr("Show Desktop");
    info.description = QObject::tr("Hide all open windows and show the desktop");
    info.ID = "homebutton";
    info.icon = "user-desktop";
  PANEL.insert(info.ID, info);
  //Start Menu
  info = LPI(); //clear it
    info.name = QObject::tr("Start Menu");
    info.description = QObject::tr("Unified system access and application launch menu.");
    info.ID = "systemstart";
    info.icon = "Lumina-DE";
  PANEL.insert(info.ID, info);
  //Application Launcher
  info = LPI(); //clear it
    info.name = QObject::tr("Application Launcher");
    info.description = QObject::tr("Pin an application shortcut directly to the panel");
    info.ID = "applauncher";
    info.icon = "quickopen";
  PANEL.insert(info.ID, info);
  //Audio Player Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Audio Player");
    info.description = QObject::tr("Play through lists of audio files");
    info.ID = "audioplayer";
    info.icon = "media-playback-start";
  PANEL.insert(info.ID, info);
}

// DESKTOP PLUGINS
void LPlugins::LoadDesktopPlugins(){
  DESKTOP.clear();
  //Calendar Plugin
  LPI info;
    info.name = QObject::tr("Calendar");
    info.description = QObject::tr("Display a calendar on the desktop");
    info.ID = "calendar";
    info.icon = "view-calendar";
  DESKTOP.insert(info.ID, info);
  //Application Launcher Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Application Launcher");
    info.description = QObject::tr("Desktop button for launching an application");
    info.ID = "applauncher";
    info.icon = "quickopen";
  DESKTOP.insert(info.ID, info);
  //Desktop View Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Desktop Icons View");
    info.description = QObject::tr("Configurable area for automatically showing desktop icons");
    info.ID = "desktopview";
    info.icon = "preferences-desktop-icons";
  DESKTOP.insert(info.ID, info);
  //Notepad Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Note Pad");
    info.description = QObject::tr("Keep simple text notes on your desktop");
    info.ID = "notepad";
    info.icon = "text-enriched";
  DESKTOP.insert(info.ID, info);
  //Audio Player Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("Audio Player");
    info.description = QObject::tr("Play through lists of audio files");
    info.ID = "audioplayer";
    info.icon = "media-playback-start";
  DESKTOP.insert(info.ID, info);
  //System Monitor Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("System Monitor");
    info.description = QObject::tr("Keep track of system statistics such as CPU/Memory usage and CPU temperatures.");
    info.ID = "systemmonitor";
    info.icon = "cpu";
  DESKTOP.insert(info.ID, info);
  //RSS Reader Plugin
  info = LPI(); //clear it
    info.name = QObject::tr("RSS Reader");
    info.description = QObject::tr("Monitor RSS Feeds (Requires internet connection)");
    info.ID = "rssreader";
    info.icon = "application-rss+xml";
  DESKTOP.insert(info.ID, info);
  //Available QtQuick scripts
  /*QStringList quickID = LUtils::listQuickPlugins();
  for(int i=0; i<quickID.length(); i++){
    QStringList quickinfo = LUtils::infoQuickPlugin(quickID[i]); //Returns: [name, description, icon]
    if(quickinfo.length() < 3){ continue; } //invalid file (unreadable/other)
    info = LPI();
      info.name = quickinfo[0];
      info.description = quickinfo[1];
      info.ID = "quick-"+quickID[i]; //the "quick-" prefix is required for the desktop plugin syntax
      info.icon = quickinfo[2];
    DESKTOP.insert(info.ID, info);
  }*/
}

//    MENU PLUGINS
void LPlugins::LoadMenuPlugins(){
  MENU.clear();
  //Terminal
  LPI info;
    info.name = QObject::tr("Terminal");
    info.description = QObject::tr("Start the default system terminal.");
    info.ID = "terminal";
    info.icon = "utilities-terminal";
  MENU.insert(info.ID, info);
  //File Manager
  info = LPI(); //clear it
    info.name = QObject::tr("Browse Files");
    info.description = QObject::tr("Browse the system with the default file manager.");
    info.ID = "filemanager";
    info.icon = "Insight-FileManager";
  MENU.insert(info.ID, info);
  //Applications
  info = LPI(); //clear it
    info.name = QObject::tr("Applications");
    info.description = QObject::tr("Show the system applications menu.");
    info.ID = "applications";
    info.icon = "system-run";
  MENU.insert(info.ID, info);
  //Line seperator
  info = LPI(); //clear it
    info.name = QObject::tr("Separator");
    info.description = QObject::tr("Static horizontal line.");
    info.ID = "line";
    info.icon = "insert-horizontal-rule";
  MENU.insert(info.ID, info);
  //Settings
  info = LPI(); //clear it
    info.name = QObject::tr("Preferences");
    info.description = QObject::tr("Show the desktop settings menu.");
    info.ID = "settings";
    info.icon = "configure";
  MENU.insert(info.ID, info);
  //Window List
  info = LPI(); //clear it
    info.name = QObject::tr("Task Manager");
    info.description = QObject::tr("List the open, minimized, active, and urgent application windows");
    info.ID = "windowlist";
    info.icon = "preferences-system-windows";
  MENU.insert(info.ID, info);
  //Custom Apps
  info = LPI(); //clear it
    info.name = QObject::tr("Custom App");
    info.description = QObject::tr("Start a custom application");
    info.ID = "app";
    info.icon = "application-x-desktop";
  MENU.insert(info.ID, info);
  //Custom Apps
  info = LPI(); //clear it
    info.name = QObject::tr("Menu Script");
    info.description = QObject::tr("Run an external script to generate a user defined menu");
    info.ID = "jsonmenu";
    info.icon = "text-x-script";
  MENU.insert(info.ID, info);
}

void LPlugins::LoadColorItems(){
  COLORS.clear();
  //Text Color
  LPI info;
    info.name = QObject::tr("Text");
    info.description = QObject::tr("Color to use for all visible text.");
    info.ID = "TEXTCOLOR";
  COLORS.insert(info.ID, info);
  //Text Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Text (Disabled)");
    info.description = QObject::tr("Text color for disabled or inactive items.");
    info.ID = "TEXTDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Text Color (Highlighted)
  info = LPI(); //clear it
    info.name = QObject::tr("Text (Highlighted)");
    info.description = QObject::tr("Text color when selection is highlighted.");
    info.ID = "TEXTHIGHLIGHTCOLOR";
  COLORS.insert(info.ID, info);
  //Base Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Base Window Color");
    info.description = QObject::tr("Main background color for the window/dialog.");
    info.ID = "BASECOLOR";
  COLORS.insert(info.ID, info);
  //Base Color (Alternate)
  info = LPI(); //clear it
    info.name = QObject::tr("Base Window Color (Alternate)");
    info.description = QObject::tr("Main background color for widgets that list or display collections of items.");
    info.ID = "ALTBASECOLOR";
  COLORS.insert(info.ID, info);
  //Primary Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Primary Color");
    info.description = QObject::tr("Dominant color for the theme.");
    info.ID = "PRIMARYCOLOR";
  COLORS.insert(info.ID, info);
  //Primary Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Primary Color (Disabled)");
    info.description = QObject::tr("Dominant color for the theme (more subdued).");
    info.ID = "PRIMARYDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Secondary Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Secondary Color");
    info.description = QObject::tr("Alternate color for the theme.");
    info.ID = "SECONDARYCOLOR";
  COLORS.insert(info.ID, info);
  //Secondary Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Secondary Color (Disabled)");
    info.description = QObject::tr("Alternate color for the theme (more subdued).");
    info.ID = "SECONDARYDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Accent Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Accent Color");
    info.description = QObject::tr("Color used for borders or other accents.");
    info.ID = "ACCENTCOLOR";
  COLORS.insert(info.ID, info);
  //Accent Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Accent Color (Disabled)");
    info.description = QObject::tr("Color used for borders or other accents (more subdued).");
    info.ID = "ACCENTDISABLECOLOR";
  COLORS.insert(info.ID, info);
  //Highlight Color (Normal)
  info = LPI(); //clear it
    info.name = QObject::tr("Highlight Color");
    info.description = QObject::tr("Color used for highlighting an item.");
    info.ID = "HIGHLIGHTCOLOR";
  COLORS.insert(info.ID, info);
  //Highlight Color (Disabled)
  info = LPI(); //clear it
    info.name = QObject::tr("Highlight Color (Disabled)");
    info.description = QObject::tr("Color used for highlighting an item (more subdued).");
    info.ID = "HIGHLIGHTDISABLECOLOR";
  COLORS.insert(info.ID, info);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 The Native Client Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "native_client/src/include/nacl_assert.h"
#include "native_client/src/trusted/service_runtime/mmap_test_check.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

#define MAX_INPUT_LINE_LENGTH   4096

void CheckMapping(uintptr_t addr, size_t size, int protect, int map_type) {
  const char *maps_path = "/proc/self/maps";
  FILE *maps_file;
  char buf[MAX_INPUT_LINE_LENGTH];
  uint64_t start;
  uint64_t end;
  int64_t inode;
  char flags[4];
  int prot = 0;
  int type = 0;
  int num;
  int found = 0;

  // Open /proc/self/maps to read process memory mapping
  maps_file = fopen(maps_path, "r");
  ASSERT(maps_file != NULL);

  for (;;) {
    // Read each line from /proc/self/maps file
    if (!fgets(buf, sizeof(buf), maps_file)) {
      break;
    }
    // Parse the line
    if (3 < sscanf(buf, "%"SCNx64"-%"SCNx64" %4s %*d %*x:%*x %"SCNd64" %n",
                   &start, &end, flags, &inode, &num)) {
      // The maps file will merge regions with the same attributes.  Thus,
      // we allow the starting address to be before the expected starting
      // address, and we allow the ending address to be after the expected
      // end address (addr + size).
      if (start <= addr && end >= addr + size) {
        if (flags[0] == 'r')
          prot |= PROT_READ;
        if (flags[1] == 'w')
          prot |= PROT_WRITE;
        if (flags[2] == 'x')
          prot |= PROT_EXEC;

        if (flags[3] == 'p')
          type |= MAP_PRIVATE;
        else if (flags[3] == 's')
          type |= MAP_SHARED;

        found = 1;
        break;
      }
    }
  }

  ASSERT(found);
  ASSERT_EQ(prot, protect);
  ASSERT_EQ(type, map_type);
  ASSERT_EQ(fclose(maps_file), 0);
}
<commit_msg>Fix ASan report in tests.<commit_after>/*
 * Copyright (c) 2012 The Native Client Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "native_client/src/include/nacl_assert.h"
#include "native_client/src/trusted/service_runtime/mmap_test_check.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

#define MAX_INPUT_LINE_LENGTH   4096

void CheckMapping(uintptr_t addr, size_t size, int protect, int map_type) {
  const char *maps_path = "/proc/self/maps";
  FILE *maps_file;
  char buf[MAX_INPUT_LINE_LENGTH];
  uint64_t start;
  uint64_t end;
  int64_t inode;
  char flags[5];
  int prot = 0;
  int type = 0;
  int num;
  int found = 0;

  // Open /proc/self/maps to read process memory mapping
  maps_file = fopen(maps_path, "r");
  ASSERT(maps_file != NULL);

  for (;;) {
    // Read each line from /proc/self/maps file
    if (!fgets(buf, sizeof(buf), maps_file)) {
      break;
    }
    // Parse the line
    if (3 < sscanf(buf, "%"SCNx64"-%"SCNx64" %4s %*d %*x:%*x %"SCNd64" %n",
                   &start, &end, flags, &inode, &num)) {
      // The maps file will merge regions with the same attributes.  Thus,
      // we allow the starting address to be before the expected starting
      // address, and we allow the ending address to be after the expected
      // end address (addr + size).
      if (start <= addr && end >= addr + size) {
        if (flags[0] == 'r')
          prot |= PROT_READ;
        if (flags[1] == 'w')
          prot |= PROT_WRITE;
        if (flags[2] == 'x')
          prot |= PROT_EXEC;

        if (flags[3] == 'p')
          type |= MAP_PRIVATE;
        else if (flags[3] == 's')
          type |= MAP_SHARED;

        found = 1;
        break;
      }
    }
  }

  ASSERT(found);
  ASSERT_EQ(prot, protect);
  ASSERT_EQ(type, map_type);
  ASSERT_EQ(fclose(maps_file), 0);
}
<|endoftext|>


<commit_before>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include <memory>
#include <spdlog/spdlog.h>
#include <string>

class logger final {
public:
  static spdlog::logger& get_logger(void) {
    static std::shared_ptr<spdlog::logger> logger;
    if (!logger) {
      if (auto p = constants::get_home_dot_karabiner_directory()) {
        std::string log_directory = p;
        mkdir(log_directory.c_str(), 0700);

        log_directory += "/log/";
        mkdir(log_directory.c_str(), 0700);

        static char hostname[_POSIX_HOST_NAME_MAX + 1];
        if (gethostname(hostname, sizeof(hostname)) == 0) {
          log_directory += hostname;
          mkdir(log_directory.c_str(), 0700);

          if (filesystem::is_directory(log_directory)) {
            std::string log_file_path = log_directory + "/karabiner_console_user_server_log";
            logger = spdlog::rotating_logger_mt("karabiner_console_user_server", log_file_path.c_str(), 5 * 1024 * 1024, 3, true);
          }
        }
      }

      if (!logger) {
        // fallback
        logger = spdlog::stdout_logger_mt("karabiner_console_user_server", true);
      }
    }
    return *logger;
  }
};
<commit_msg>change log location<commit_after>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include <memory>
#include <spdlog/spdlog.h>
#include <string>

class logger final {
public:
  static spdlog::logger& get_logger(void) {
    static std::shared_ptr<spdlog::logger> logger;
    if (!logger) {
      if (auto p = constants::get_home_dot_karabiner_directory()) {
        std::string log_directory = p;
        mkdir(log_directory.c_str(), 0700);

        log_directory += "/log/";
        mkdir(log_directory.c_str(), 0700);

        if (filesystem::is_directory(log_directory)) {
          std::string log_file_path = log_directory + "/karabiner_console_user_server_log";
          logger = spdlog::rotating_logger_mt("karabiner_console_user_server", log_file_path.c_str(), 5 * 1024 * 1024, 3, true);
        }
      }

      if (!logger) {
        // fallback
        logger = spdlog::stdout_logger_mt("karabiner_console_user_server", true);
      }
    }
    return *logger;
  }
};
<|endoftext|>


<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_native_system_math.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    Library_nf_native_system_math_System_Math::Abs___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Abs___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Acos___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Acos___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Asin___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Asin___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Atan___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Atan___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Atan2___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Atan2___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Ceiling___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Ceiling___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Cos___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Cos___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Cosh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Cosh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Exp___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Exp___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Floor___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Floor___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Log___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Log___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Log10___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Log10___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Max___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Max___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Min___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Min___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Pow___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Pow___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Round___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Round___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R8,
    Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R4,
    Library_nf_native_system_math_System_Math::Sin___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sin___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sinh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sinh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sqrt___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sqrt___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Tan___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Tan___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Tanh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Tanh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Truncate___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Truncate___STATIC__R4__R4,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Math =
{
    "System.Math",
    0x4BDCF00F,
    method_lookup,
    { 1, 0, 2, 2 }
};
<commit_msg>Update nanoFramework.System.Math version to 1.0.4 ***NO_CI***<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_native_system_math.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    NULL,
    NULL,
    Library_nf_native_system_math_System_Math::Abs___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Abs___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Acos___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Acos___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Asin___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Asin___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Atan___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Atan___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Atan2___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Atan2___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Ceiling___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Ceiling___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Cos___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Cos___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Cosh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Cosh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Exp___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Exp___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Floor___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Floor___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Log___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Log___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Log10___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Log10___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Max___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Max___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Min___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Min___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Pow___STATIC__R8__R8__R8,
    Library_nf_native_system_math_System_Math::Pow___STATIC__R4__R4__R4,
    Library_nf_native_system_math_System_Math::Round___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Round___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R8,
    Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R4,
    Library_nf_native_system_math_System_Math::Sin___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sin___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sinh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sinh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Sqrt___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Sqrt___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Tan___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Tan___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Tanh___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Tanh___STATIC__R4__R4,
    Library_nf_native_system_math_System_Math::Truncate___STATIC__R8__R8,
    Library_nf_native_system_math_System_Math::Truncate___STATIC__R4__R4,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Math =
{
    "System.Math",
    0x4BDCF00F,
    method_lookup,
    { 1, 0, 4, 3 }
};
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#if defined XALAN_ICU_MSG_LOADER

// Class header file.
#include "XalanICUMessageLoader.hpp"

#include "PlatformSupportInit.hpp"

#include "DOMStringHelper.hpp"

#include "unicode/uloc.h"

#include "unicode/udata.h"

#include <xercesc/util/XMLMsgLoader.hpp>

#include <xercesc/util/XMLString.hpp>

#include "xalanc/Include/XalanVersion.hpp"

#define XALAN_MESSAGES_NAME XalanMessages

#define XALAN_MESSAGES_NAME_W_UNDERSCORE INVK_CAT2_RAW_NUMERIC(XALAN_MESSAGES_NAME,_)

#define MAKE_STRING(a) #a
#define INVK_MAKE_STRING(a) MAKE_STRING(a)

#ifdef WIN32

#ifdef  NDEBUG_SYMBOLS // release with symbols

#define ENTRY_POINT_SUFFIX S_dat
#define PACKAGE_NAME_SUFFIX S

#elif NDEBUG // release

#define ENTRY_POINT_SUFFIX _dat
#define PACKAGE_NAME_SUFFIX

#elif _DEBUG // debug only

#define ENTRY_POINT_SUFFIX D_dat
#define PACKAGE_NAME_SUFFIX D

#endif // NDEBUG_SYMBOLS

#define ICUDLL_ENTRYPOINT_NAME INVK_CAT3_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,\
									INVK_CAT2_RAW_NUMERIC_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR),\
									ENTRY_POINT_SUFFIX)

#define PACKAGE_NAME INVK_CAT3_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,\
									INVK_CAT2_RAW_NUMERIC_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR),\
									PACKAGE_NAME_SUFFIX)

#else // NON-WIN32 systems

#define ICUDLL_ENTRYPOINT_NAME INVK_CAT2_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,dat)

#define PACKAGE_NAME XALAN_MESSAGES_NAME

#endif // WIN32

static const char* const	sPackageName=INVK_MAKE_STRING(PACKAGE_NAME);

extern "C" const char U_IMPORT  ICUDLL_ENTRYPOINT_NAME [];

XALAN_CPP_NAMESPACE_BEGIN

XALAN_USING_XERCES(XMLMsgLoader)

XALAN_USING_XERCES(XMLString)

// ---------------------------------------------------------------------------
//  Local static methods
// ---------------------------------------------------------------------------

/*
 *  Resource Data Reference.
 *
 *  The data is packaged as a dll (or .so or whatever, depending on the platform) that exports a data symbol.
 *  The application (thic *.cpp) references that symbol here, and will pass the data address to ICU, which
 *  will then  be able to fetch resources from the data.
 */

static const char* domainName = INVK_MAKE_STRING(XALAN_PRODUCT);

XalanICUMessageLoader::XalanICUMessageLoader(MemoryManagerType &theManager):
	m_localeBundle(0),
	m_domainBundle(0),
	m_unknownMessage(XALAN_STATIC_UCODE_STRING("The message was not found in the ICU resource bundle."), theManager)
{
 	UErrorCode err = U_ZERO_ERROR;

	udata_setAppData(sPackageName, &ICUDLL_ENTRYPOINT_NAME, &err);

	if (! U_SUCCESS(err))
	{
		assert( 0 );
	}
	const char* szLocal = XMLMsgLoader::getLocale();
	if ( szLocal == 0 )
	{
		// Opps , we failed to get local from Xerces, let's try our
		szLocal="en_US";
	}

	m_localeBundle = ures_open(sPackageName, szLocal , &err);
	if (!U_SUCCESS(err) || m_localeBundle == 0)
	{
		assert( 0 );
	}

	err = U_ZERO_ERROR;
    m_domainBundle = ures_getByKey(m_localeBundle, domainName, 0, &err);
    if (!U_SUCCESS(err) || m_domainBundle == 0)
    {
        assert( 0 );
    }
}

XalanICUMessageLoader::~XalanICUMessageLoader()
{
	ures_close(m_domainBundle);
	ures_close(m_localeBundle);
}

bool XalanICUMessageLoader::loadMsg(XalanMessages::Codes    msgToLoad
									, XalanDOMChar*		toFill
									, unsigned int      maxChars)
{

   bool bResult = true;
   UErrorCode   err = U_ZERO_ERROR;
   int32_t      strLen = 0;

   // Assuming array format
   const UChar * const	name = ures_getStringByIndex(m_domainBundle, (int32_t)msgToLoad+1, &strLen, &err);

   if (!U_SUCCESS(err) || (name == 0))
   {
	   XalanCopy(m_unknownMessage.c_str(), m_unknownMessage.c_str() + m_unknownMessage.length() + 1, toFill);

	   return false;
   }

   const unsigned int	retStrLen = unsigned(strLen + 1 ) > maxChars ? maxChars : unsigned(strLen + 1);

   XalanCopy(name, name + retStrLen, toFill);

   return bResult;
}

XALAN_CPP_NAMESPACE_END

#endif // defined (XALAN_ICU_MSG_LOADER)

<commit_msg>temporary fix for a build Xalan-C with ICU Win32/Unix<commit_after>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#if defined XALAN_ICU_MSG_LOADER

// Class header file.
#include "XalanICUMessageLoader.hpp"

#include "PlatformSupportInit.hpp"

#include "DOMStringHelper.hpp"

#include "unicode/uloc.h"

#include "unicode/udata.h"

#include <xercesc/util/XMLMsgLoader.hpp>

#include <xercesc/util/XMLString.hpp>

#include "xalanc/Include/XalanVersion.hpp"

#ifdef WIN32
#define XALAN_MESSAGES_NAME XalanMessages
#else
#define XALAN_MESSAGES_NAME xalanMsg
#endif

#define XALAN_MESSAGES_NAME_W_UNDERSCORE INVK_CAT2_RAW_NUMERIC(XALAN_MESSAGES_NAME,_)

#define MAKE_STRING(a) #a
#define INVK_MAKE_STRING(a) MAKE_STRING(a)

#ifdef WIN32

#ifdef  NDEBUG_SYMBOLS // release with symbols

#define ENTRY_POINT_SUFFIX S_dat
#define PACKAGE_NAME_SUFFIX S

#elif NDEBUG // release

#define ENTRY_POINT_SUFFIX _dat
#define PACKAGE_NAME_SUFFIX

#elif _DEBUG // debug only

#define ENTRY_POINT_SUFFIX D_dat
#define PACKAGE_NAME_SUFFIX D

#endif // NDEBUG_SYMBOLS

#define ICUDLL_ENTRYPOINT_NAME INVK_CAT3_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,\
									INVK_CAT2_RAW_NUMERIC_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR),\
									ENTRY_POINT_SUFFIX)

#define PACKAGE_NAME INVK_CAT3_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,\
									INVK_CAT2_RAW_NUMERIC_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR),\
									PACKAGE_NAME_SUFFIX)

#else // NON-WIN32 systems

#define ICUDLL_ENTRYPOINT_NAME INVK_CAT2_RAW_NUMERIC(XALAN_MESSAGES_NAME_W_UNDERSCORE,dat)

#define PACKAGE_NAME XALAN_MESSAGES_NAME

#endif // WIN32

static const char* const	sPackageName=INVK_MAKE_STRING(PACKAGE_NAME);

extern "C" const char U_IMPORT  ICUDLL_ENTRYPOINT_NAME [];

XALAN_CPP_NAMESPACE_BEGIN

XALAN_USING_XERCES(XMLMsgLoader)

XALAN_USING_XERCES(XMLString)

// ---------------------------------------------------------------------------
//  Local static methods
// ---------------------------------------------------------------------------

/*
 *  Resource Data Reference.
 *
 *  The data is packaged as a dll (or .so or whatever, depending on the platform) that exports a data symbol.
 *  The application (thic *.cpp) references that symbol here, and will pass the data address to ICU, which
 *  will then  be able to fetch resources from the data.
 */

static const char* domainName = INVK_MAKE_STRING(XALAN_PRODUCT);

XalanICUMessageLoader::XalanICUMessageLoader(MemoryManagerType &theManager):
	m_localeBundle(0),
	m_domainBundle(0),
	m_unknownMessage(XALAN_STATIC_UCODE_STRING("The message was not found in the ICU resource bundle."), theManager)
{
 	UErrorCode err = U_ZERO_ERROR;

	udata_setAppData(sPackageName, &ICUDLL_ENTRYPOINT_NAME, &err);

	if (! U_SUCCESS(err))
	{
		assert( 0 );
	}
	const char* szLocal = XMLMsgLoader::getLocale();
	if ( szLocal == 0 )
	{
		// Opps , we failed to get local from Xerces, let's try our
		szLocal="en_US";
	}

	m_localeBundle = ures_open(sPackageName, szLocal , &err);
	if (!U_SUCCESS(err) || m_localeBundle == 0)
	{
		assert( 0 );
	}

	err = U_ZERO_ERROR;
    m_domainBundle = ures_getByKey(m_localeBundle, domainName, 0, &err);
    if (!U_SUCCESS(err) || m_domainBundle == 0)
    {
        assert( 0 );
    }
}

XalanICUMessageLoader::~XalanICUMessageLoader()
{
	ures_close(m_domainBundle);
	ures_close(m_localeBundle);
}

bool XalanICUMessageLoader::loadMsg(XalanMessages::Codes    msgToLoad
									, XalanDOMChar*		toFill
									, unsigned int      maxChars)
{

   bool bResult = true;
   UErrorCode   err = U_ZERO_ERROR;
   int32_t      strLen = 0;

   // Assuming array format
   const UChar * const	name = ures_getStringByIndex(m_domainBundle, (int32_t)msgToLoad+1, &strLen, &err);

   if (!U_SUCCESS(err) || (name == 0))
   {
	   XalanCopy(m_unknownMessage.c_str(), m_unknownMessage.c_str() + m_unknownMessage.length() + 1, toFill);

	   return false;
   }

   const unsigned int	retStrLen = unsigned(strLen + 1 ) > maxChars ? maxChars : unsigned(strLen + 1);

   XalanCopy(name, name + retStrLen, toFill);

   return bResult;
}

XALAN_CPP_NAMESPACE_END

#endif // defined (XALAN_ICU_MSG_LOADER)

<|endoftext|>


<commit_before>#ifndef COFFEE_MILL_UTIL_LOGGER_HPP
#define COFFEE_MILL_UTIL_LOGGER_HPP
#include <map>
#include <iostream>
#include <cstdint>

namespace mill
{
namespace log
{
enum class level : std::uint8_t
{
    error,
    warn ,
    info ,
    debug,
};

struct Logger
{
    Logger(): filter_{{level::debug, false}, {level::info,  true},
                      {level::warn,  true},  {level::error, true}}
    {}
    ~Logger() = default;

    bool is_activated(const level lv) const {return filter_.at(lv);}

    void activate  (const level lv) {filter_[lv] = true;}
    void deactivate(const level lv) {filter_[lv] = false;}

  private:
    std::map<level, bool> filter_;
};
inline Logger logger;

template<typename ... Ts>
void error(Ts&& ... args)
{
    if(not logger.is_activated(level::error)) {return;}
    std::cerr << "\x1b[31mError:\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::flush;
    return;
}
template<typename ... Ts>
void warn(Ts&& ... args)
{
    if(not logger.is_activated(level::warn)) {return;}
    std::cerr << "\x1b[33mWarn :\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::flush;
    return;
}
template<typename ... Ts>
void info(Ts&& ... args)
{
    if(not logger.is_activated(level::info)) {return;}
    std::cerr << "\x1b[32mInfo :\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::flush;
    return;
}
template<typename ... Ts>
void debug(Ts&& ... args)
{
    if(not logger.is_activated(level::debug)) {return;}
    std::cerr << "\x1b[34mDebug:\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::flush;
    return;
}

} // log
} // mill
#endif// COFFEE_MILL_UTIL_LOGGER_HPP
<commit_msg>:lipstick: always output LF at the end of log<commit_after>#ifndef COFFEE_MILL_UTIL_LOGGER_HPP
#define COFFEE_MILL_UTIL_LOGGER_HPP
#include <map>
#include <iostream>
#include <cstdint>

namespace mill
{
namespace log
{
enum class level : std::uint8_t
{
    error,
    warn ,
    info ,
    debug,
};

struct Logger
{
    Logger(): filter_{{level::debug, false}, {level::info,  true},
                      {level::warn,  true},  {level::error, true}}
    {}
    ~Logger() = default;

    bool is_activated(const level lv) const {return filter_.at(lv);}

    void activate  (const level lv) {filter_[lv] = true;}
    void deactivate(const level lv) {filter_[lv] = false;}

  private:
    std::map<level, bool> filter_;
};
inline Logger logger;

template<typename ... Ts>
void error(Ts&& ... args)
{
    if(not logger.is_activated(level::error)) {return;}
    std::cerr << "\x1b[31mError:\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::endl;
    return;
}
template<typename ... Ts>
void warn(Ts&& ... args)
{
    if(not logger.is_activated(level::warn)) {return;}
    std::cerr << "\x1b[33mWarn :\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::endl;
    return;
}
template<typename ... Ts>
void info(Ts&& ... args)
{
    if(not logger.is_activated(level::info)) {return;}
    std::cerr << "\x1b[32mInfo :\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::endl;
    return;
}
template<typename ... Ts>
void debug(Ts&& ... args)
{
    if(not logger.is_activated(level::debug)) {return;}
    std::cerr << "\x1b[34mDebug:\x1b[0m ";
    (std::cerr << ... << args);
    std::cerr << std::endl;
    return;
}

} // log
} // mill
#endif// COFFEE_MILL_UTIL_LOGGER_HPP
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <cassert>

#include "boost/format.hpp"

#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MDGModifier.h"
#include "maya/MGlobal.h"
#include "maya/MItGeometry.h"
#include "maya/MObjectArray.h"
#include "maya/MPlug.h"
#include "maya/MPlugArray.h"
#include "maya/MSelectionList.h"

#include "IECore/SmoothSkinningData.h"
#include "IECore/PrimitiveVariable.h"
#include "IECore/MessageHandler.h"

#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaSkinClusterConverter.h"

using namespace IECoreMaya;

ToMayaSkinClusterConverter::Description ToMayaSkinClusterConverter::g_skinClusterDescription( IECore::SmoothSkinningData::staticTypeId(), MFn::kSkinClusterFilter );

ToMayaSkinClusterConverter::ToMayaSkinClusterConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "Converts IECore::SmoothSkinningData objects to a Maya skinCluster.", object)
{
}

bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
	MStatus s;

	IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from );
	assert( skinningData );

	const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable();
	const std::vector<Imath::M44f> &influencePoseData  = skinningData->influencePose()->readable();
	const std::vector<int> &pointIndexOffsets  = skinningData->pointIndexOffsets()->readable();
	const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable();
	const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable();
	const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable();

	MFnDependencyNode fnSkinClusterNode( to, &s );
	MFnSkinCluster fnSkinCluster( to, &s );
	if ( s != MS::kSuccess )
	{
		/// \todo: optional parameter to allow custom node types and checks for the necessary attributes
		/// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one
		throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() );
	}

	// gather the influence objects
	/// \todo: optional parameter to keep existing influences
	MObject mObj;
	MDagPath path;
	MSelectionList influenceList;
	MDagPathArray influencePaths;
	for ( unsigned i=0; i < influenceNames.size(); i++ )
	{
		MString influenceName( influenceNames[i].c_str() );
		influenceList.add( influenceName );
		s = influenceList.getDependNode( i, mObj );
		if ( s != MS::kSuccess )
		{
			throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: Influence \"%s\" does not exist" ) % influenceName ).str() );
		}
		MFnDagNode fnInfluence( mObj, &s );
		fnInfluence.getPath( path );
		influencePaths.append( path );
	}

	/// \todo: optional parameter to reset the skinCluster's geomMatrix plug

	// break existing influence connections to the skinCluster
	MDGModifier dgModifier;
	MPlugArray connectedPlugs;
	MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s );
	for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ )
	{
		MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s );
		matrixPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], matrixPlug );
	}
	MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s );
	for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ )
	{
		MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s );
		lockPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], lockPlug );
	}
	MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s );
	paintPlug.connectedTo( connectedPlugs, true, false );
	if ( connectedPlugs.length() )
	{
		dgModifier.disconnect( connectedPlugs[0], paintPlug );
	}

	// break existing influence connections to the bind pose
	MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s );
	bindPlug.connectedTo( connectedPlugs, true, false );
	MFnDependencyNode fnBindPose( connectedPlugs[0].node() );
	MPlug bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s );
	for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ )
	{
		MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s );
		matrixPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], matrixPlug );
	}
	MPlug bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s );
	for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ )
	{
		MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s );
		memberPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], memberPlug );
	}
	dgModifier.doIt();

	// make connections from influences to skinCluster and bindPose
	for ( unsigned i=0; i < influenceNames.size(); i++ )
	{
		influenceList.getDependNode( i, mObj );
		MFnDependencyNode fnInfluence( mObj );
		MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s );
		MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
		MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
		MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s );

		// connect influence to the skinCluster
		MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( i );
		MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( i );
		dgModifier.connect( influenceMatrixPlug, matrixPlug );
		dgModifier.connect( influenceLockPlug, lockPlug );

		// connect influence to the bindPose
		MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( i );
		MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( i );
		dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug );
		dgModifier.connect( influenceBindPosePlug, memberPlug );
	}
	influenceList.getDependNode( 0, mObj );
	MFnDependencyNode fnInfluence( mObj );
	MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
	dgModifier.connect( influenceMessagePlug, paintPlug );
	dgModifier.doIt();

	// use influencePoseData as bindPreMatrix
	MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s );
	for ( unsigned i=0; i < influencePoseData.size(); i++ )
	{
		MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s );
		preMatrixPlug.getValue( mObj );
		MFnMatrixData matFn( mObj, &s );
		matFn.set( IECore::convert<MMatrix>( influencePoseData[i] ) );
		mObj = matFn.object();
		preMatrixPlug.setValue( mObj );
	}

	// get the geometry
	MObjectArray outputGeoObjs;
	if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) )
	{
		throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() );
	}
	MFnDagNode dagFn( outputGeoObjs[0] );
	MDagPath geoPath;
	dagFn.getPath( geoPath );

	// loop through all the points of the geometry and set the weights
	MItGeometry geoIt( outputGeoObjs[0] );
	MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s );
	for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ )
	{
		MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 );

		// remove existing influence weight plugs
		MIntArray existingInfluenceIndices;
		pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices );
		for( unsigned i=0; i < existingInfluenceIndices.length(); i++ )
		{
			MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s );
			MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() );
		}

		// add new influence weight plugs
		int firstIndex = pointIndexOffsets[pIndex];
		for( int i=0; i < pointInfluenceCounts[pIndex]; i++ )
		{
			int influenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ pointInfluenceIndices[ firstIndex + i ] ] );
			MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( influenceIndex, &s );
			influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] );
		}
	}

	return true;
}
<commit_msg>creating lockInfluenceWeights attribute if it doesnt exist<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <cassert>

#include "boost/format.hpp"

#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MDGModifier.h"
#include "maya/MGlobal.h"
#include "maya/MItGeometry.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MObjectArray.h"
#include "maya/MPlug.h"
#include "maya/MPlugArray.h"
#include "maya/MSelectionList.h"

#include "IECore/SmoothSkinningData.h"
#include "IECore/PrimitiveVariable.h"
#include "IECore/MessageHandler.h"

#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaSkinClusterConverter.h"

using namespace IECoreMaya;

ToMayaSkinClusterConverter::Description ToMayaSkinClusterConverter::g_skinClusterDescription( IECore::SmoothSkinningData::staticTypeId(), MFn::kSkinClusterFilter );

ToMayaSkinClusterConverter::ToMayaSkinClusterConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "Converts IECore::SmoothSkinningData objects to a Maya skinCluster.", object)
{
}

bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
	MStatus s;

	IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from );
	assert( skinningData );

	const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable();
	const std::vector<Imath::M44f> &influencePoseData  = skinningData->influencePose()->readable();
	const std::vector<int> &pointIndexOffsets  = skinningData->pointIndexOffsets()->readable();
	const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable();
	const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable();
	const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable();

	MFnDependencyNode fnSkinClusterNode( to, &s );
	MFnSkinCluster fnSkinCluster( to, &s );
	if ( s != MS::kSuccess )
	{
		/// \todo: optional parameter to allow custom node types and checks for the necessary attributes
		/// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one
		throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() );
	}

	// gather the influence objects
	/// \todo: optional parameter to keep existing influences
	MObject mObj;
	MDagPath path;
	MSelectionList influenceList;
	MDagPathArray influencePaths;
	for ( unsigned i=0; i < influenceNames.size(); i++ )
	{
		MString influenceName( influenceNames[i].c_str() );
		influenceList.add( influenceName );
		s = influenceList.getDependNode( i, mObj );
		if ( s != MS::kSuccess )
		{
			throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: Influence \"%s\" does not exist" ) % influenceName ).str() );
		}
		MFnDagNode fnInfluence( mObj, &s );
		fnInfluence.getPath( path );
		influencePaths.append( path );
	}

	/// \todo: optional parameter to reset the skinCluster's geomMatrix plug

	// break existing influence connections to the skinCluster
	MDGModifier dgModifier;
	MPlugArray connectedPlugs;
	MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s );
	for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ )
	{
		MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s );
		matrixPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], matrixPlug );
	}
	MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s );
	for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ )
	{
		MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s );
		lockPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], lockPlug );
	}
	MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s );
	paintPlug.connectedTo( connectedPlugs, true, false );
	if ( connectedPlugs.length() )
	{
		dgModifier.disconnect( connectedPlugs[0], paintPlug );
	}

	// break existing influence connections to the bind pose
	MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s );
	bindPlug.connectedTo( connectedPlugs, true, false );
	MFnDependencyNode fnBindPose( connectedPlugs[0].node() );
	MPlug bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s );
	for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ )
	{
		MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s );
		matrixPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], matrixPlug );
	}
	MPlug bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s );
	for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ )
	{
		MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s );
		memberPlug.connectedTo( connectedPlugs, true, false );
		dgModifier.disconnect( connectedPlugs[0], memberPlug );
	}
	dgModifier.doIt();

	// make connections from influences to skinCluster and bindPose
	for ( unsigned i=0; i < influenceNames.size(); i++ )
	{
		influenceList.getDependNode( i, mObj );
		MFnDependencyNode fnInfluence( mObj );
		MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s );
		MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
		MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s );
		MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
		if ( !s )
		{
			// add the lockInfluenceWeights attribute if it doesn't exist
			MFnNumericAttribute nAttr;
			MObject attribute = nAttr.create( "lockInfluenceWeights", "liw", MFnNumericData::kBoolean, false );
			fnInfluence.addAttribute( attribute );
			influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
		}

		// connect influence to the skinCluster
		MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( i );
		MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( i );
		dgModifier.connect( influenceMatrixPlug, matrixPlug );
		dgModifier.connect( influenceLockPlug, lockPlug );

		// connect influence to the bindPose
		MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( i );
		MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( i );
		dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug );
		dgModifier.connect( influenceBindPosePlug, memberPlug );
	}
	influenceList.getDependNode( 0, mObj );
	MFnDependencyNode fnInfluence( mObj );
	MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
	dgModifier.connect( influenceMessagePlug, paintPlug );
	dgModifier.doIt();

	// use influencePoseData as bindPreMatrix
	MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s );
	for ( unsigned i=0; i < influencePoseData.size(); i++ )
	{
		MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s );
		preMatrixPlug.getValue( mObj );
		MFnMatrixData matFn( mObj, &s );
		matFn.set( IECore::convert<MMatrix>( influencePoseData[i] ) );
		mObj = matFn.object();
		preMatrixPlug.setValue( mObj );
	}

	// get the geometry
	MObjectArray outputGeoObjs;
	if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) )
	{
		throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() );
	}
	MFnDagNode dagFn( outputGeoObjs[0] );
	MDagPath geoPath;
	dagFn.getPath( geoPath );

	// loop through all the points of the geometry and set the weights
	MItGeometry geoIt( outputGeoObjs[0] );
	MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s );
	for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ )
	{
		MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 );

		// remove existing influence weight plugs
		MIntArray existingInfluenceIndices;
		pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices );
		for( unsigned i=0; i < existingInfluenceIndices.length(); i++ )
		{
			MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s );
			MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() );
		}

		// add new influence weight plugs
		int firstIndex = pointIndexOffsets[pIndex];
		for( int i=0; i < pointInfluenceCounts[pIndex]; i++ )
		{
			int influenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ pointInfluenceIndices[ firstIndex + i ] ] );
			MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( influenceIndex, &s );
			influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] );
		}
	}

	return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2007  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include <pwd.h>
#include <map>
#include <vector>

class CPerform : public CModule
{
public:
	MODCONSTRUCTOR(CPerform)
	{
	}

	virtual ~CPerform()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		GetNV("Perform").Split("\n", m_vPerform, false);

		return true;
	}

	virtual void OnModCommand( const CString& sCommand )
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if(sCmdName == "add")
		{
			CString sPerf = sCommand.Token(1, true);
			if(sPerf.Left(1) == "/")
				sPerf.LeftChomp();

			if(sPerf.Token(0).CaseCmp("MSG") == 0) {
				sPerf = "PRIVMSG " + sPerf.Token(1, true);
			}

			if((sPerf.Token(0).CaseCmp("PRIVMSG") == 0 ||
				sPerf.Token(0).CaseCmp("NOTICE") == 0) &&
				sPerf.Token(2).Left(1) != ":") {
				sPerf = sPerf.Token(0) + " " + sPerf.Token(1)
					+ " :" + sPerf.Token(2, true);
			}
			m_vPerform.push_back(sPerf);
			PutModule("Added!");
			Save();
		} else if(sCmdName == "del")
		{
			u_int iNum = atoi( sCommand.Token(1, true).c_str() );
			if ( iNum > m_vPerform.size() || iNum <= 0 )
			{
				PutModule( "Illegal # Requested");
				return;
			}
			else
			{
				m_vPerform.erase( m_vPerform.begin() + iNum - 1 );
				PutModule( "Command Erased.");
			}
			Save();
		} else if(sCmdName == "list")
		{
			int i = 1;
			CString sExpanded;
			for(VCString::iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, i++)
			{
				sExpanded = GetUser()->ExpandString( *it );
				if(sExpanded != *it)
					PutModule(CString( i ) + ": " + *it + " (" + sExpanded + ")");
				else
					PutModule(CString( i ) + ": " + *it);
			}
			PutModule(" -- End of List");
		} else if(sCmdName == "save")
		{
			if(Save())
				PutModule("Saved!");
			else
				PutModule("Error");
		}else
		{
			PutModule( "Commands: add <command>, del <nr>, list, save");
		}
	}

	virtual void OnIRCConnected()
	{
		for( VCString::iterator it = m_vPerform.begin();
			it != m_vPerform.end();  it++)
		{
			PutIRC( GetUser()->ExpandString( *it ) );
		}
	}

private:
	bool Save()
	{
		CString sBuffer = "";

		for(VCString::iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++)
		{
			sBuffer += *it + "\n";
		}
		SetNV("Perform", sBuffer);

		return true;
	}

	VCString	m_vPerform;
};

MODULEDEFS(CPerform, "Adds perform capabilities")
<commit_msg>Remove save command for perform, add and del already save everything<commit_after>/*
 * Copyright (C) 2004-2007  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include <pwd.h>
#include <map>
#include <vector>

class CPerform : public CModule
{
public:
	MODCONSTRUCTOR(CPerform)
	{
	}

	virtual ~CPerform()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		GetNV("Perform").Split("\n", m_vPerform, false);

		return true;
	}

	virtual void OnModCommand( const CString& sCommand )
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if(sCmdName == "add")
		{
			CString sPerf = sCommand.Token(1, true);
			if(sPerf.Left(1) == "/")
				sPerf.LeftChomp();

			if(sPerf.Token(0).CaseCmp("MSG") == 0) {
				sPerf = "PRIVMSG " + sPerf.Token(1, true);
			}

			if((sPerf.Token(0).CaseCmp("PRIVMSG") == 0 ||
				sPerf.Token(0).CaseCmp("NOTICE") == 0) &&
				sPerf.Token(2).Left(1) != ":") {
				sPerf = sPerf.Token(0) + " " + sPerf.Token(1)
					+ " :" + sPerf.Token(2, true);
			}
			m_vPerform.push_back(sPerf);
			PutModule("Added!");
			Save();
		} else if(sCmdName == "del")
		{
			u_int iNum = atoi( sCommand.Token(1, true).c_str() );
			if ( iNum > m_vPerform.size() || iNum <= 0 )
			{
				PutModule( "Illegal # Requested");
				return;
			}
			else
			{
				m_vPerform.erase( m_vPerform.begin() + iNum - 1 );
				PutModule( "Command Erased.");
			}
			Save();
		} else if(sCmdName == "list")
		{
			int i = 1;
			CString sExpanded;
			for(VCString::iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++, i++)
			{
				sExpanded = GetUser()->ExpandString( *it );
				if(sExpanded != *it)
					PutModule(CString( i ) + ": " + *it + " (" + sExpanded + ")");
				else
					PutModule(CString( i ) + ": " + *it);
			}
			PutModule(" -- End of List");
		}else
		{
			PutModule( "Commands: add <command>, del <nr>, list");
		}
	}

	virtual void OnIRCConnected()
	{
		for( VCString::iterator it = m_vPerform.begin();
			it != m_vPerform.end();  it++)
		{
			PutIRC( GetUser()->ExpandString( *it ) );
		}
	}

private:
	bool Save()
	{
		CString sBuffer = "";

		for(VCString::iterator it = m_vPerform.begin(); it != m_vPerform.end(); it++)
		{
			sBuffer += *it + "\n";
		}
		SetNV("Perform", sBuffer);

		return true;
	}

	VCString	m_vPerform;
};

MODULEDEFS(CPerform, "Adds perform capabilities")
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_data.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/optimizer/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/optimizer/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::ErrorCode;
using common::TrajectoryPoint;
using common::VehicleState;

EMPlanner::EMPlanner() {}

void EMPlanner::RegisterOptimizers() {
  optimizer_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Optimizer* {
    return new DpPolyPathOptimizer("DpPolyPathOptimizer");
  });
  optimizer_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Optimizer* {
    return new DpStSpeedOptimizer("DpStSpeedOptimizer");
  });
  optimizer_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Optimizer* {
    return new QpSplinePathOptimizer("QpSplinePathOptimizer");
  });
  optimizer_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Optimizer* {
    return new QpSplineStSpeedOptimizer("QpSplineStSpeedOptimizer");
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterOptimizers();
  for (int i = 0; i < config.em_planner_config().optimizer_size(); ++i) {
    optimizers_.emplace_back(optimizer_factory_.CreateObject(
        config.em_planner_config().optimizer(i)));
    AINFO << "Created optimizer:" << optimizers_.back()->name();
  }
  for (auto& optimizer : optimizers_) {
    if (!optimizer->Init()) {
      std::string msg(common::util::StrCat("Init optimizer[", optimizer->name(),
                                           "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

Status EMPlanner::MakePlan(const TrajectoryPoint& start_point,
                           ADCTrajectory* trajectory_pb) {
  DataCenter* data_center = DataCenter::instance();
  Frame* frame = data_center->current_frame();

  if (data_center->last_frame()) {
    ADEBUG << "last frame:" << data_center->last_frame()->DebugString();
  }
  ADEBUG << "start point:" << start_point.DebugString();
  auto planning_data = frame->mutable_planning_data();
  planning_data->set_init_planning_point(start_point);

  std::shared_ptr<DecisionData> decision_data(new DecisionData());

  planning_data->set_decision_data(decision_data);
  for (auto& optimizer : optimizers_) {
    optimizer->Optimize(planning_data);
    ADEBUG << "after optimizer " << optimizer->name() << ":"
           << planning_data->DebugString();
  }
  PublishableTrajectory computed_trajectory;
  if (!planning_data->aggregate(FLAGS_output_trajectory_time_resolution,
                                &computed_trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  frame->set_computed_trajectory(computed_trajectory);
  computed_trajectory.populate_trajectory_protobuf(trajectory_pb);

  // Add debug information.
  auto* debug_reference_line =
      trajectory_pb->mutable_debug()->mutable_planning_data()->add_path();
  debug_reference_line->set_name("planning_reference_line");
  const auto& reference_points =
      planning_data->reference_line().reference_points();
  debug_reference_line->mutable_path()->mutable_path_point()->CopyFrom({
      reference_points.begin(), reference_points.end()});

  return Status::OK();
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const double init_v, const double init_a) {
  // TODO(@lianglia-apollo): this is a dummy simple hot start, need refine later
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = init_v;

  // start acceleration
  start_state[2] = init_a;

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = 10.0;

  // end state acceleration
  end_state[1] = 0.0;

  // pre assume the curve time is 8 second, can be change later
  QuarticPolynomialCurve1d speed_curve(start_state, end_state,
                                       FLAGS_trajectory_time_length);

  // assume the time resolution is 0.1
  std::uint32_t num_time_steps =
      static_cast<std::uint32_t>(FLAGS_trajectory_time_length /
                                 FLAGS_trajectory_time_resolution) +
      1;
  std::vector<SpeedPoint> speed_profile;
  speed_profile.reserve(num_time_steps);

  for (std::uint32_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_curve.evaluate(0, t);
    double v = speed_curve.evaluate(1, t);
    double a = speed_curve.evaluate(2, t);
    double da = speed_curve.evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    speed_profile.push_back(speed_point);
  }
  return std::move(speed_profile);
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Store reference line debug information only when enabled.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_data.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/optimizer/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/optimizer/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/optimizer/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::ErrorCode;
using common::TrajectoryPoint;
using common::VehicleState;

EMPlanner::EMPlanner() {}

void EMPlanner::RegisterOptimizers() {
  optimizer_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Optimizer* {
    return new DpPolyPathOptimizer("DpPolyPathOptimizer");
  });
  optimizer_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Optimizer* {
    return new DpStSpeedOptimizer("DpStSpeedOptimizer");
  });
  optimizer_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Optimizer* {
    return new QpSplinePathOptimizer("QpSplinePathOptimizer");
  });
  optimizer_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Optimizer* {
    return new QpSplineStSpeedOptimizer("QpSplineStSpeedOptimizer");
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterOptimizers();
  for (int i = 0; i < config.em_planner_config().optimizer_size(); ++i) {
    optimizers_.emplace_back(optimizer_factory_.CreateObject(
        config.em_planner_config().optimizer(i)));
    AINFO << "Created optimizer:" << optimizers_.back()->name();
  }
  for (auto& optimizer : optimizers_) {
    if (!optimizer->Init()) {
      std::string msg(common::util::StrCat("Init optimizer[", optimizer->name(),
                                           "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

Status EMPlanner::MakePlan(const TrajectoryPoint& start_point,
                           ADCTrajectory* trajectory_pb) {
  DataCenter* data_center = DataCenter::instance();
  Frame* frame = data_center->current_frame();

  if (data_center->last_frame()) {
    ADEBUG << "last frame:" << data_center->last_frame()->DebugString();
  }
  ADEBUG << "start point:" << start_point.DebugString();
  auto planning_data = frame->mutable_planning_data();
  planning_data->set_init_planning_point(start_point);

  std::shared_ptr<DecisionData> decision_data(new DecisionData());

  planning_data->set_decision_data(decision_data);
  for (auto& optimizer : optimizers_) {
    optimizer->Optimize(planning_data);
    ADEBUG << "after optimizer " << optimizer->name() << ":"
           << planning_data->DebugString();
  }
  PublishableTrajectory computed_trajectory;
  if (!planning_data->aggregate(FLAGS_output_trajectory_time_resolution,
                                &computed_trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  frame->set_computed_trajectory(computed_trajectory);
  computed_trajectory.populate_trajectory_protobuf(trajectory_pb);

  // Add debug information.
  if (FLAGS_enable_record_debug) {
    auto* debug_reference_line =
        trajectory_pb->mutable_debug()->mutable_planning_data()->add_path();
    debug_reference_line->set_name("planning_reference_line");
    const auto& reference_points =
        planning_data->reference_line().reference_points();
    debug_reference_line->mutable_path()->mutable_path_point()->CopyFrom({
        reference_points.begin(), reference_points.end()});
  }

  return Status::OK();
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const double init_v, const double init_a) {
  // TODO(@lianglia-apollo): this is a dummy simple hot start, need refine later
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = init_v;

  // start acceleration
  start_state[2] = init_a;

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = 10.0;

  // end state acceleration
  end_state[1] = 0.0;

  // pre assume the curve time is 8 second, can be change later
  QuarticPolynomialCurve1d speed_curve(start_state, end_state,
                                       FLAGS_trajectory_time_length);

  // assume the time resolution is 0.1
  std::uint32_t num_time_steps =
      static_cast<std::uint32_t>(FLAGS_trajectory_time_length /
                                 FLAGS_trajectory_time_resolution) +
      1;
  std::vector<SpeedPoint> speed_profile;
  speed_profile.reserve(num_time_steps);

  for (std::uint32_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_curve.evaluate(0, t);
    double v = speed_curve.evaluate(1, t);
    double a = speed_curve.evaluate(2, t);
    double da = speed_curve.evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    speed_profile.push_back(speed_point);
  }
  return std::move(speed_profile);
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>