id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
754,019
|
bytearray.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/bytearray.hpp
|
#ifndef BYTE_ARRAY_H
#define BYTE_ARRAY_H
#include <string>
#include <deque>
#include <stdint.h>
#include <stdio.h>
#include "journal.hpp"
#ifdef putc
#undef putc
#endif
namespace utils
{
namespace model
{
/** @brief A raw array of bytes */
class ByteArray
{
public:
void lis_fichier(FILE *fi, uint32_t lon);
void ecris_fichier(FILE *fo);
int ecris_fichier(const std::string &fn);
int lis_fichier(const std::string &fn);
ByteArray(int len);
ByteArray();
ByteArray(const unsigned char *buffer, unsigned int len, bool bigendian = false);
ByteArray(const ByteArray &ba);
//ByteArray(unsigned char x);
ByteArray(std::string str, bool is_decimal = true);
void operator =(const ByteArray &ba);
const unsigned char &operator[](unsigned int i) const;
unsigned char &operator[](unsigned int i);
ByteArray operator +(const ByteArray &ba) const;
ByteArray operator +(unsigned char c) const;
bool operator ==(const ByteArray &ba) const;
bool operator !=(const ByteArray &ba) const;
void clear();
void put(const ByteArray &ba);
void putc(uint8_t c);
void putw(uint16_t w);
void putl(uint32_t l);
void putL(uint64_t val);
void put(const void *buffer, unsigned int len);
/** Put nullptr terminated string */
void puts_zt(std::string s);
void puts(std::string s);
void putf(float f);
uint32_t size() const;
uint8_t popc();
uint16_t popw();
uint32_t popl();
uint64_t popL();
std::string pops();
float popf();
void pop_data(void *buffer, uint32_t len);
void pop(ByteArray &ba, uint32_t len);
std::string to_string(bool hexa = false) const;
void insert(uint8_t c);
std::deque<unsigned char> data;
bool bigendian;
};
}
}
#endif
| 1,811
|
C++
|
.h
| 63
| 26.206349
| 83
| 0.67128
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,020
|
journal.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/journal.hpp
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef TRACE_HPP
#define TRACE_HPP
#include <stdarg.h>
#include <stdint.h>
#include <string>
#include <vector>
#include <assert.h>
namespace utils
{
/** Debug printf (disabled at global niveau by default, to enable,
* use, "set_debug_options" function below). */
//extern void verbose(const char *s, ...);
//extern void infos(const char *s, ...);
//extern void trace_majeure(const char *s, ...);
//extern void avertissement(const char *s, ...);
//extern void erreur(const char *s, ...);
namespace journal
{
/** @brief The different infos levels (criticity) */
typedef enum
{
/** @brief Verbose infos, for internal debugging only */
AL_VERBOSE = 1,
/** @brief Normal infos niveau */
AL_NORMAL = 2,
/** @brief Normal infos niveau */
AL_MAJOR = 4,
/** @brief Non critical warning */
AL_WARNING = 8,
/** @brief Critical */
AL_ANOMALY = 16,
/** @brief To disable all infos levels */
AL_NONE = 17
} TraceLevel;
/** @brief Destination des traces */
typedef enum trace_target_enum
{
/** Stdout / stderr */
TRACE_TARGET_STD = 0,
/** Log file */
TRACE_TARGET_FILE = 1,
TRACE_TARGET_NONE = 2
} TraceTarget;
/** @brief An object to write timestamped debug infos (logs) */
class Logable
{
public:
Logable(const std::string &module = "");
/** Setup the category of the log:
* @param module Typically project / component name. */
void setup(const std::string &module);
//private:
std::string module_id;
void set_min_level(TraceTarget target, TraceLevel min_level);
TraceLevel min_levels[2];
};
extern void gen_trace(TraceLevel niveau, const std::string &module, const Logable &log, const std::string &s, va_list ap);
extern void gen_trace(TraceLevel niveau, const std::string &module, const Logable &log, const std::string &s, ...);
extern void gen_trace(TraceLevel niveau, const std::string &module, const std::string &s, ...);
/** Setup infos modes */
extern void set_log_file(std::string filename);
/** Enable / disable all traces */
extern void enable_all(bool enabled);
/** Set global minimum infos niveau */
extern void set_global_min_level(TraceTarget target, TraceLevel min_level);
extern TraceLevel get_global_min_level(TraceTarget target);
extern void set_abort_on_anomaly(bool abort);
extern uint32_t get_anomaly_count();
extern uint32_t get_warning_count();
/** @brief Abstract interface to an output receptacle for infos logs */
class Tracer
{
public:
virtual ~Tracer(){}
virtual void gen_trace(int trace_level, const std::string &module, const std::string &message) = 0;
virtual void flush() = 0;
};
extern Logable journal_principal;
//#ifdef DEBUG_MODE
# define trace_verbeuse(...) utils::journal::gen_trace(utils::journal::AL_VERBOSE, __func__, __VA_ARGS__)
//#else
//# define trace_verbeuse(...)
//#endif
#define infos(...) utils::journal::gen_trace(utils::journal::AL_NORMAL, __func__, __VA_ARGS__)
#define trace_majeure(...) utils::journal::gen_trace(utils::journal::AL_MAJOR, __func__, __VA_ARGS__)
#define avertissement(...) utils::journal::gen_trace(utils::journal::AL_WARNING, __func__, __VA_ARGS__)
#define erreur(...) utils::journal::gen_trace(utils::journal::AL_ANOMALY, __func__, __VA_ARGS__)
/** @brief Display an error message in the log before asserting */
#define lassert(AA, ...) if(!(AA)){utils::journal::gen_trace(utils::journal::AL_WARNING, __func__, ##__VA_ARGS__); utils::journal::gen_trace(utils::journal::AL_ANOMALY, __func__, "Assertion failed: " #AA ".\nFile: %s, line: %d, func: %s", __FILE__, __LINE__, __func__); assert(AA);}
/** @brief Returns -1 if the condition is not true (and add an error message in the log) */
#define rassert(AA, ...) if(!(AA)){utils::journal::gen_trace(utils::journal::AL_WARNING, __func__, ##__VA_ARGS__); utils::journal::gen_trace(utils::journal::AL_ANOMALY, __func__, "Assertion failed: " #AA ".\nFile: %s, line: %d", __FILE__, __LINE__); return -1;}
#ifdef DEBUG_MODE
# define lassert_safe(...) lassert(__VA_ARGS__)
#else
# define lassert_safe(...)
#endif
#ifdef DEBUG_MODE
# define rassert_safe(...) rassert(__VA_ARGS__)
#else
# define rassert_safe(...)
#endif
// infos("bla bla %d", 54);
// infos(log, "bla bla %d", 54);
}
} // namespace utils
#endif
| 5,147
|
C++
|
.h
| 124
| 38.508065
| 282
| 0.672164
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,021
|
cutil.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/cutil.hpp
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef _CUTIL_H
#define _CUTIL_H
#include "mxml.hpp"
#include "slots.hpp"
#include <string>
#include <stdint.h>
#include <vector>
#ifdef BLACKFIN
#define __func__ ""
#define nullptr 0
#endif
/** @brief Portable miscellaneous functions */
namespace utils
{
/** @cond not-documented */
template <class T>
class refcnt
{
public:
T *ptr;
int count;
};
/** @endcond */
/** @brief Reference counting shared pointer (until std::shared_ptr supported natively by visual dsp)
*
* TODO: remove and replace by std::shared_ptr (NOT UNTIL VISUAL DSP COMPILER SUPPORT C++11).
* */
template <typename T>
class refptr
{
public:
explicit refptr(T *p)
{
reference = new refcnt<T>();
reference->ptr = p;
reference->count = 1;
}
explicit refptr(const T& t)
{
reference = new refcnt<T>();
reference->ptr = new T(t);
reference->count = 1;
}
/*explicit refptr(T *p, void (T:: *tell_container)(refcnt<T> *ptr))
{
reference = new refcnt<T>();
reference->ptr = p;
reference->count = 1;
// Tell the contained class its unique container.
if(tell_container != 0)
{
p->tell_container(reference);
}
}*/
refptr()
{
reference = nullptr;
}
bool is_nullptr() const
{
return reference == nullptr;
}
bool operator ==(const refptr &r) const
{
return reference == r.reference;
}
refptr &operator =(const refptr &r)
{
if(r.reference != nullptr)
r.reference->count++;
if((reference != nullptr) && (r.reference != reference))
{
reference->count--;
if(reference->count <= 0)
{
delete reference->ptr;
delete reference;
reference = nullptr;
}
}
reference = r.reference;
return *this;
}
refptr(const refptr &r)
{
reference = nullptr;
*(this) = r;
}
T *get_reference()
{
if(reference == nullptr)
return nullptr;
return reference->ptr;
}
~refptr()
{
if(reference != nullptr)
{
reference->count--;
if(reference->count == 0)
{
if(reference->ptr != nullptr)
{
delete reference->ptr;
reference->ptr = nullptr;
}
delete reference;
reference = nullptr;
}
}
}
T &operator*()
{
return *(reference->ptr);
}
const T &operator*() const
{
return *(reference->ptr);
}
T *operator->()
{
return reference->ptr;
}
const T *operator->() const
{
return reference->ptr;
}
//private: // (to uncomment)
refcnt<T> *reference;
explicit refptr(refcnt<T> *rcnt)
{
reference = rcnt;
if(reference != nullptr)
reference->count++;
}
};
template <typename T>
class uptr
{
public:
explicit uptr(T *p)
{
ptr = p;
}
explicit uptr(const T &p)
{
ptr = new T(p);
}
/*explicit refptr(T *p, void (T:: *tell_container)(refcnt<T> *ptr))
{
reference = new refcnt<T>();
reference->ptr = p;
reference->count = 1;
// Tell the contained class its unique container.
if(tell_container != 0)
{
p->tell_container(reference);
}
}*/
uptr()
{
ptr = nullptr;
}
bool is_nullptr() const
{
return ptr == nullptr;
}
bool operator ==(const uptr &r) const
{
return *(r.ptr) == *ptr;
}
uptr &operator =(const uptr &r)
{
if(r.ptr != nullptr)
ptr = new T(*(r.ptr));
else
ptr = nullptr;
return *this;
}
uptr(const uptr &r)
{
ptr = nullptr;
*(this) = r;
}
T *get_reference()
{
if(ptr == nullptr)
return nullptr;
return ptr;
}
~uptr()
{
if(ptr != nullptr)
{
delete ptr;
ptr = nullptr;
}
}
T &operator*()
{
return *ptr;
}
const T &operator*() const
{
return *ptr;
}
T *operator->()
{
return ptr;
}
const T *operator->() const
{
return ptr;
}
private:
T *ptr;
explicit uptr(uptr<T> *rcnt)
{
ptr = new T(*(rcnt->ptr));
}
};
/** @cond not-documented */
template <class T>
class arraycnt
{
public:
T *ptr;
int count;
};
/** @endcond */
/** @brief Reference counting shared pointer (until std::shared_ptr supported natively by visual dsp)
*
* TODO: remove and replace by std::shared_ptr (NOT UNTIL VISUAL DSP COMPILER SUPPORT C++11).
* */
template <typename T>
class arrayptr
{
public:
explicit arrayptr(T *p)
{
reference = new arraycnt<T>();
reference->ptr = p;
reference->count = 1;
}
/*explicit refptr(T *p, void (T:: *tell_container)(refcnt<T> *ptr))
{
reference = new refcnt<T>();
reference->ptr = p;
reference->count = 1;
// Tell the contained class its unique container.
if(tell_container != 0)
{
p->tell_container(reference);
}
}*/
arrayptr()
{
reference = nullptr;
}
bool is_nullptr() const
{
return reference == nullptr;
}
bool operator ==(const arrayptr &r) const
{
return reference == r.reference;
}
arrayptr &operator =(const arrayptr &r)
{
if(r.reference != nullptr)
r.reference->count++;
if((reference != nullptr) && (r.reference != reference))
{
reference->count--;
if(reference->count <= 0)
{
delete [] reference->ptr;
reference->ptr = nullptr;
delete reference;
reference = nullptr;
}
}
reference = r.reference;
return *this;
}
arrayptr(const arrayptr &r)
{
reference = nullptr;
*(this) = r;
}
T *get_reference()
{
if(reference == nullptr)
return nullptr;
return reference->ptr;
}
~arrayptr()
{
if(reference != nullptr)
{
reference->count--;
if(reference->count == 0)
{
if(reference->ptr != nullptr)
{
delete [] reference->ptr;
reference->ptr = nullptr;
}
delete reference;
reference = nullptr;
}
}
}
T &operator*()
{
return *(reference->ptr);
}
T *operator->()
{
return reference->ptr;
}
const T *operator->() const
{
return reference->ptr;
}
//private: // (to uncomment)
arraycnt<T> *reference;
explicit arrayptr(arraycnt<T> *rcnt)
{
reference = rcnt;
if(reference != nullptr)
reference->count++;
}
};
namespace model
{
/** @brief A localized string, in UTF 8. */
class Localized
{
public:
/** Different languages */
typedef enum LanguageEnum
{
/** Unlocalized identifier, used for identification in the code */
LANG_ID = 0,
/** Currently configured language */
LANG_CURRENT = 1,
/** French */
LANG_FR = 2,
/** English */
LANG_EN = 3,
/** German */
LANG_DE = 4,
/** Russian */
LANG_RU = 5,
LANG_ES = 6,
/** Unspecified language */
LANG_UNKNOWN = 255
} Language;
static Language current_language;
Localized();
Localized(const Localized &l);
Localized(const utils::model::MXml &mx);
void operator =(const Localized &l);
void set_value(Language lg, std::string value);
void set_description(Language lg, std::string desc);
/** @brief Get the value in the specified language (by default "ID language") */
std::string get_value(Language lg = LANG_ID) const;
/** @brief Equivalent to get_value(LANG_CURRENT) */
std::string get_localized() const;
/** @brief Equivalent to get_value(LANG_ID) */
inline std::string get_id() const {return id;}
/** @brief Get the HTML description in the specified language */
std::string get_description(Language lg = LANG_CURRENT) const;
bool has_description() const;
/** @brief Parse language string ("fr" -> LANG_FR, "en" -> LANG_EN, ...) */
static Language parse_language(std::string id);
static std::string language_id(Language l);
static std::vector<Language> language_list();
std::string to_string() const;
private:
/** @brief The different values in different languages, in UTF8 format. */
std::vector<std::pair<Language, std::string> > items;
/** @brief The different descriptions in different languages, in UTF8 format. */
std::vector<std::pair<Language, std::string> > descriptions;
std::string id;
};
}
/** @brief Command line argument parsing */
class CmdeLine
{
public:
CmdeLine(const std::string args);
CmdeLine(int argc, const char **argv);
CmdeLine(int argc, char **argv);
CmdeLine();
void operator =(const CmdeLine &cmdeline);
bool has_option(const std::string &name) const;
std::string get_option(const std::string &name,
const std::string &default_value = "") const;
int get_int_option(const std::string &name,
int default_value) const;
void set_option(const std::string &name, const std::string &value);
private:
void init(std::vector<std::string> &lst);
void init(int argc, const char **argv);
class CmdeLinePrm
{
public:
std::string option;
std::string value;
};
std::deque<CmdeLinePrm> prms;
public:
//int argc;
std::string argv0;
};
/** @brief Initialise paths and analyse standard command line options.
* Options managed:
* - [-v] : enable debug infos on stdout
* - [-L fr|en|de] : specify current language
* - [-q] : disable log files.
*
* @param cmdeline Command line arguments.
* @param projet Name of the project (used to define the application data folders).
* @param app Name of the application */
extern void init(CmdeLine &cmde_line,
const std::string &projet,
const std::string &app = "",
unsigned int vmaj = 0,
unsigned int vmin = 0,
unsigned int vpatch = 0);
extern void init(int argc, const char **argv,
const std::string &projet,
const std::string &app = "",
unsigned int vmaj = 0,
unsigned int vmin = 0,
unsigned int vpatch = 0);
/** @brief Read an environment variable */
extern std::string get_env_variable(const std::string &name, const std::string &default_value = "");
/** @brief Path to fixed data (same as exec path for windows, /usr/share/appname for linux) */
extern std::string get_fixed_data_path();
/** @brief Get the path to the current user parameters directory (e.g. C:\\Doc and Settings\\CURRENT_USER\\AppData\\AppName) */
extern std::string get_current_user_path();
/** @brief Get the path to the current user document directory (e.g. C:\\Doc and Settings\\CURRENT_USER\\AppName) */
extern std::string get_current_user_doc_path();
/** @brief Get the path to path the all user parameters directory (e.g. C:\\Doc and Settings\\All Users\\AppData\\AppName) */
extern std::string get_all_user_path();
/** @brief Path to local images (returns img sub-folder of fixed data path. */
extern std::string get_img_path();
/** @brief Return the path containing the currently executed module . */
extern std::string get_execution_path();
extern std::string get_current_date_time();
/** Execute a system command, block until it is finished. */
extern int proceed_syscmde(std::string cmde, ...);
/** Execute a system command, returns immediatly. */
extern int proceed_syscmde_bg(std::string cmde, ...);
/** @brief Static utilities functions */
class Util
{
public:
#ifndef TESTCLI
static void show_error(std::string title, std::string content);
static void show_warning(std::string title, std::string content);
#endif
static uint32_t extract_bits(uint8_t *buffer, uint32_t offset_in_bits, uint32_t nbits);
};
namespace str
{
std::string to_latex(const std::string s);
std::string str_to_cst(std::string name);
std::string str_to_var(std::string name);
std::string str_to_class(std::string name);
std::string str_to_file(std::string name);
/** Returns an abbridged version of the specified file path (for display purpose) */
std::string get_filename_resume(const std::string &filename, unsigned int max_chars = 30);
bool is_deci(char c);
bool is_hexa(char c);
/** @brief Convert an integer to "x bytes", "x kbi", "x mbi", "y gbi" */
std::string int2str_capacity(uint64_t val, bool truncate = false);
std::string int2str(int i);
std::string int2str(int i, int nb_digits);
std::string int2strhexa(int i);
std::string int2strhexa(int i, int nbits);
std::string uint2strhexa(int i);
std::string int2strasm(int i);
std::string xmlAtt(std::string name, std::string val);
std::string xmlAtt(std::string name, int val);
std::string xmlAtt(std::string name, bool val);
std::string latin_to_utf8(std::string s_);
std::string utf8_to_latin(std::string s);
std::string lowercase(std::string s);
int parse_int_list(const std::string s, std::vector<int> &res);
int parse_string_list(const std::string s, std::vector<std::string> &res, char separator);
int parse_hexa_list(const std::string s, std::vector<unsigned char> &res);
void encode_str(std::string str, std::vector<unsigned char> vec);
void encode_byte_array_deci(std::string str, std::vector<unsigned char> vec);
void encode_byte_array_hexa(std::string str, std::vector<unsigned char> vec);
std::string unix_path_to_win_path(std::string s_);
}
namespace files
{
bool file_exists(std::string name);
bool dir_exists(std::string name);
int copy_file(std::string target, std::string source);
int creation_dossier(std::string path);
int explore_dossier(std::string chemin, std::vector<std::string> &fichiers);
//int liste_dossier(const std::string &path, std::vector<std::string> &res);
/** @brief If the directory does not exist, try to create it. */
int check_and_build_directory(std::string path);
void split_path_and_filename(const std::string complete_filename, std::string &path, std::string &filename);
std::string get_path_separator();
std::string correct_path_separators(std::string s);
std::string build_absolute_path(const std::string absolute_origin, const std::string relative_path);
void delete_file(std::string name);
int save_txt_file(std::string filename, std::string content);
/** @brief Retrieve file extension from a file path
* Example: from "a.jpg", returns "jpg". */
std::string get_extension(const std::string &filepath);
std::string remove_extension(const std::string &filepath);
int parse_filepath(const std::string &path,
std::vector<std::string> &items);
int abs2rel(const std::string &ref,
const std::string &abs,
std::string &result);
int rel2abs(const std::string &ref,
const std::string &rel,
std::string &result);
void remplacement_motif(std::string &chemin);
}
class TextAlign
{
public:
TextAlign();
void add(std::string comment);
void add(std::string s1, std::string s2);
void add(std::string s1, std::string s2, std::string s3);
std::string get_result();
private:
std::vector<std::string > alst1;
std::vector<std::string > alst2;
std::vector<std::string > alst3;
std::vector<std::string > comments;
std::vector<unsigned int> comments_pos;
};
class TextMatrix
{
public:
TextMatrix(uint32_t ncols);
void add(std::string s);
void add_unformatted_line(std::string s);
void next_line();
std::string get_result();
void reset(uint32_t ncols);
private:
uint32_t ncols;
std::vector<std::string> current_row;
std::vector<std::vector<std::string> > lst;
std::vector<bool> unformatted;
};
// TODO: rename
class Section
{
public:
Section();
Section(const Section &c);
~Section();
void operator =(const Section &c);
bool has_item(const std::string &name) const;
std::string get_item(const std::string &name) const;
const utils::model::Localized &get_localized(const std::string &name) const;
Section &get_section(const std::string &name);
const Section &get_section(const std::string &name) const;
void load();
void load(std::string filename);
void load(const utils::model::MXml &data);
private:
Section(const utils::model::MXml &data);
std::vector<utils::model::Localized> elmts;
std::vector<utils::refptr<Section>> subs;
std::string nom;
};
class Test
{
public:
virtual int proceed() = 0;
};
/** @brief Test framework */
class TestUtil
{
public:
TestUtil(const utils::CmdeLine &cmdeline);
TestUtil(const std::string &module, const std::string &prg, int argc, const char **argv);
int add_test(const std::string &name, int (*test_routine)());
int add_test(const std::string &name, Test *test);
int proceed();
/** @param precision: relative precision, in percent. */
static int check_value(float v, float ref, float precision = 0.0, const std::string &refname = "");
private:
class TestUnit
{
public:
std::string name;
int (*test_routine)();
Test *test;
};
std::vector<TestUnit> units;
utils::CmdeLine cmdeline;
};
/** @brief Command line, as defined by the application */
class CmdeLineDefinition
{
public:
/** @brief Load the command line definition from an XML string.
*
*
* // PB: temps de chargement std-schema...
* <schema name="cmdeline-spec" root="cmdeline-spec">
* <node name="cmdeline-spec">
* <sub-node name="arg" inherits="attribute"/>
* </node>
* </schema>
*
*
* Example:
* <cmdeline>
* <arg name="i" mandatory="true" fr="Fichier d'entrée">
* <description lang="fr">Chemin complet du fichier d'entrée</description>
* </arg>
* </cmdeline>
*/
int from_xml(const std::string &xml_definition);
/** @brief Display usage info on the specified output stream */
void usage(std::ostream &out) const;
/** @returns 0 if cmdeline is valid, otherwise display an error message.
* also, recognize and manage --help and --usage commands, and in this case,
* exits silently. */
int check_cmdeline(const CmdeLine &cmdeline) const;
/** exit(-1) if cmdeline is not valid. */
void check_cmdeline_and_fail(const CmdeLine &cmdeline) const;
private:
class Prm
{
public:
model::Localized name;
enum type
{
TP_FILE = 0, // file path
TP_EXFILE = 1, // existing file path
TP_INT = 2, // integer
TP_STRING = 3 // string
};
bool mandatory;
bool has_default;
std::string default_value;
std::string value;
};
std::vector<Prm> prms;
};
template<class VT, class T>
bool contains(const VT &container, const T &t)
{
for(const T &t2: container)
{
if(t2 == t)
return true;
}
return false;
}
#ifdef LINUX
# define PATH_SEP "/"
#else
# define PATH_SEP "\\"
#endif
# ifdef SAFE_MODE
# define assert_safe(EE) assert((EE))
# else
# define assert_safe(EE)
# endif
extern Section langue;
}
#include "templates/cutil-private.hpp"
#endif /* _CUTIL_H */
| 19,510
|
C++
|
.h
| 701
| 23.92582
| 127
| 0.654631
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,022
|
hal.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/hal.hpp
|
#ifndef HAL_HPP
#define HAL_HPP
#ifdef WIN
# include <windows.h>
#endif
#include <stdint.h>
#include <deque>
#include <string>
#include <vector>
/** @file hal.hpp
* @brief OS abstraction layer */
namespace utils
{
/** @brief Portable miscellaneous functions */
namespace hal
{
template<class A>
void thread_start(A *target_class,
void (A:: *target_function)(),
std::string name = "anonymous");
extern void sleep(uint32_t ms);
/** Tick counts in ms */
extern uint64_t get_tick_count_ms();
/** Tick counts in µs */
extern uint64_t get_tick_count_us();
extern void os_thread_start(void *prm);
extern uint64_t get_native_tick_counter();
extern uint32_t ticks_to_ms(uint64_t ticks);
extern uint64_t ticks_to_us(uint64_t ticks);
/** @brief Portable mutex class */
class Mutex
{
public:
Mutex();
~Mutex();
void lock();
void unlock();
private:
# ifdef LINUX
pthread_mutex_t mutex;
# else
CRITICAL_SECTION critical;
# endif
};
/** @brief Portable signal class */
class Signal
{
public:
Signal();
~Signal();
void raise();
void clear();
void wait();
int wait(unsigned int timeout);
static int wait_multiple(unsigned int timeout, std::vector<Signal *> sigs);
bool is_raised();
# ifdef WIN
HANDLE get_handle();
# endif
private:
# ifdef LINUX
pthread_cond_t cvar;
pthread_mutex_t mutex;
int cnt;
# else
HANDLE handle;
# endif
};
/** @brief Portable thread-safe FIFO class */
template<typename T>
class Fifo
{
public:
/** @brief Build a fifo with the specified number of "T" elements. */
Fifo(uint32_t capacity = 16);
/** @brief Push an element in the fifo. Blocks the caller if fifo is full. */
void push(T t);
/** @brief Push n elements in the fifo.
* Blocks the caller if fifo space is to short. */
void push(const T *t, uint32_t nelem);
/** @brief Pop an element from the fifo.
* Blocks the caller if fifo is empty. */
T pop();
int pop_with_timeout(uint32_t timeout_ms, T &res);
/** @brief Pop n elements from the fifo.
* Blocks the caller if the fifo do not contain enough elements. */
int pop(T *t, uint32_t nelem, uint32_t timeout);
/** @returns true if the fifo is full */
bool full() const;
/** @returns true if the fifo is empty */
bool empty() const;
/** @brief Clear the FIFO */
void clear();
uint32_t size() const;
private:
Mutex mutex;
public:
uint32_t capacity;
private:
std::deque<T> list;
public:
Signal h_not_full, h_not_empty;
};
/** @cond not-documented */
class ThreadFunctor
{
public:
virtual void call() = 0;
};
template <class A>
class SpecificThreadFunctor: public ThreadFunctor
{
public:
SpecificThreadFunctor(A *object, void (A::*m_function)())
{
this->object = object;
this->m_function = m_function;
}
virtual void call()
{
(*object.*m_function)();
}
private:
void (A::*m_function)();
A *object;
};
/** @endcond */
/** @brief Raw fifo of unformated data (bytes) */
class RawFifo
{
public:
RawFifo(uint32_t capacity);
~RawFifo();
uint32_t write(void *data, uint32_t size);
uint32_t read (void *data, uint32_t size, uint32_t timeout);
bool full();
bool empty();
void clear();
void deblock();
void reblock();
int size();
private:
Mutex mutex;
uint32_t capacity;
uint32_t fifo_first, fifo_size;
uint8_t *buffer;
Signal h_not_full, h_not_empty;
bool deblocked;
};
}
}
#endif
| 3,434
|
C++
|
.h
| 152
| 19.980263
| 79
| 0.6875
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,023
|
mxml.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mxml.hpp
|
#ifndef MXML_H
#define MXML_H
#include <vector>
#include <string>
#include "journal.hpp"
namespace utils
{
namespace model
{
class XmlAttribute
{
public:
XmlAttribute();
XmlAttribute(std::string name, std::string value);
XmlAttribute(const XmlAttribute &a);
XmlAttribute &operator =(const XmlAttribute &a);
std::string name;
std::string string_value;
int to_int() const;
bool to_bool() const;
std::string to_string() const;
double to_double() const;
};
/** @brief Objet xml */
class MXml
{
public:
std::string name;
std::vector<XmlAttribute> attributes;
std::vector<MXml> children;
std::vector<std::string> text;
// Indique l'ordre des �l�ment (true = element, false = text)
std::vector<bool> order;
MXml();
MXml(const MXml &mx);
MXml &operator =(const MXml &mx);
void add_child(const MXml &mx);
void add_text(std::string s);
/** Charge un fichier xml */
int from_file(std::string filename);
int from_string(std::string s);
MXml(std::string name, std::vector<XmlAttribute> *attributes, std::vector<MXml> *children);
std::string dump() const;
std::string dump_content() const;
std::vector<MXml> get_children(std::string name) const;
void get_children(std::string name, std::vector<const MXml *> &res) const;
std::string get_name() const;
MXml get_child(std::string name) const;
MXml get_child(std::string balise_name, std::string att_name, std::string att_value);
XmlAttribute get_attribute(std::string name) const;
bool has_attribute(std::string name) const;
bool has_child(std::string name) const;
bool has_child(std::string balise_name, std::string att_name, std::string att_value) const;
/** @brief convert "&" to "&", "\\" to "\r\n" */
static std::string xml_string_to_ascii(std::string s);
/** @brief convert "&" to "&" */
static std::string ascii_string_to_xml(std::string s);
};
}
}
#endif
| 1,927
|
C++
|
.h
| 61
| 28.639344
| 93
| 0.697888
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,024
|
cutil-private.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/templates/cutil-private.hpp
|
#ifndef CUTIL_PRIVATE_HPP
#define CUTIL_PRIVATE_HPP
#include "cutil.hpp"
#include "hal.hpp"
#ifdef WIN
//#include <windows.h>
#include <process.h>
#endif
/** @cond not-documented */
namespace utils{ namespace hal{
template <class A>
void thread_start(A *target_class,
void (A:: *target_function)(),
/*__attribute__((unused))*/ std::string name)
{
SpecificThreadFunctor<A> *stf = new SpecificThreadFunctor<A>(target_class, target_function);
# ifdef WIN
_beginthread(&utils::hal::os_thread_start, /*64000*/0, stf);
# elif defined(LINUX)
pthread_t thread_id;// = (pthread_t *) malloc(sizeof(pthread_t));
pthread_attr_t attr;
if(pthread_attr_init(&attr))
{
perror("pthread_attr_init");
return; // EINVAL, ENOMEM
}
if(pthread_attr_setstacksize(&attr, 64000))
{
perror("pthread_attr_setstacksize");
return; // EINVAL, ENOSYS
}
if(pthread_create(&thread_id,
&attr,
(void*(*)(void*))&utils::hal::os_thread_start,
stf))
{
perror("pthead_create");
return;
}
# endif
}
template<typename T>
Fifo<T>::Fifo(uint32_t capacity)
{
this->capacity = capacity;
}
template<typename T>
void Fifo<T>::push(T t)
{
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = list.size();
mutex.unlock();
if(lsize < capacity)
break;
h_not_full.wait();
}
mutex.lock();
h_not_full.raise();
list.push_back(t);
h_not_empty.raise();
mutex.unlock();
}
template<typename T>
uint32_t Fifo<T>::size() const
{
/*uint32_t res;
mutex.lock();
res = list.size();
mutex.unlock();
return res;*/
return list.size();
}
template<typename T>
void Fifo<T>::push(const T *t, uint32_t nelem)
{
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = list.size();
mutex.unlock();
if(lsize + nelem < capacity)
break;
h_not_full.wait();
}
mutex.lock();
h_not_full.raise();
for(uint32_t i = 0; i < nelem; i++)
list.push_back(t[i]);
h_not_empty.raise();
mutex.unlock();
}
template<typename T>
int Fifo<T>::pop(T *t, uint32_t nelem, uint32_t timeout)
{
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = list.size();
mutex.unlock();
if(lsize >= nelem)
break;
if(h_not_empty.wait(timeout))
return 0;
}
h_not_empty.raise();
mutex.lock();
for(uint32_t i = 0; i < nelem; i++)
{
t[i] = list[0];
list.pop_front();
}
mutex.unlock();
h_not_full.raise();
return nelem;
}
template<typename T>
int Fifo<T>::pop_with_timeout(uint32_t timeout_ms, T &res)
{
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = list.size();
mutex.unlock();
if(lsize > 0)
break;
if(h_not_empty.wait(timeout_ms))
return -1;
}
h_not_empty.raise();
mutex.lock();
res = list[0];
list.pop_front();
mutex.unlock();
h_not_full.raise();
return 0;
}
template<typename T>
T Fifo<T>::pop()
{
T res;
for(;;)
{
uint32_t lsize;
mutex.lock();
lsize = list.size();
mutex.unlock();
if(lsize > 0)
break;
h_not_empty.wait();
}
h_not_empty.raise();
mutex.lock();
res = list[0];
list.pop_front();
mutex.unlock();
h_not_full.raise();
return res;
}
template<typename T>
bool Fifo<T>::full() const
{
return list.size() == capacity;
}
template<typename T>
bool Fifo<T>::empty() const
{
return list.size() == 0;
}
template<typename T>
void Fifo<T>::clear()
{
mutex.lock();
list.clear();
h_not_full.raise();
mutex.unlock();
}
}}
/** @endcond */
#endif
| 3,586
|
C++
|
.h
| 185
| 15.837838
| 94
| 0.611423
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,025
|
modele-private.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/templates/modele-private.hpp
|
#ifndef MODELE_PRIVATE_HPP
#define MODELE_PRIVATE_HPP
namespace utils
{
namespace model
{
/** @cond not-documented */
/** @internal
* @brief An abstract class for implementing a node */
class NodePatron: public CProvider<ChangeEvent>,
protected CListener<ChangeEvent>
{
public:
friend class Node;
friend class ChangeEvent;
NodePatron();
virtual ~NodePatron(){}
///////////////////////////////////////////////////////////
//// METHODES VIRTUELLES PURES A IMPLEMENTER (PATRON) ////
///////////////////////////////////////////////////////////
virtual void add_vector(std::string name, void *data, uint32_t n);
virtual void get_vector(std::string name, uint32_t index, void *data, uint32_t n);
// GET CHILDREN, TYPE PRECISE
virtual unsigned long get_children_count(const std::string &type) const = 0;
virtual Node get_child_at(const std::string &type, unsigned int i) = 0;
virtual const Node get_child_at(const std::string &type, unsigned int i) const = 0;
virtual unsigned long get_children_count(int type) const = 0;
virtual Node get_child_at(int type, unsigned int i) = 0;
virtual const Node get_child_at(int type, unsigned int i) const = 0;
// GET ATTRIBUTES
virtual unsigned long get_attribute_count() const = 0;
virtual Attribute *get_attribute_at(unsigned int i) = 0;
virtual const Attribute *get_attribute_at(unsigned int i) const = 0;
// MODIFY
virtual Node add_child(const std::string sub_name) = 0;
virtual void add_children(const std::string &type, const std::vector<const MXml *> &lst) = 0;
virtual void remove_child(Node child) = 0;
// REFERENCES
virtual unsigned int get_reference_count() const = 0;
virtual void set_reference(const std::string &name, Node e) = 0;
virtual void set_reference(const std::string &name, const XPath &path) = 0;
virtual XPath get_reference_path(const std::string &name) = 0;
virtual const Node get_reference_at(unsigned int i, std::string &name) const = 0;
virtual Node get_parent() = 0;
virtual std::string class_name() const;
void reference();
void dereference();
virtual void discard() {}
void lock();
void unlock();
int nb_references;
NodeSchema *schema;
std::string type;
static journal::Logable log;
protected:
bool ignore;
bool change_detected;
ChangeEvent last_change;
/** Instance number inside parent */
int instance;
bool inhibit_event_raise;
bool event_detected;
private:
bool locked;
};
/** @internal
* @brief Concrete RAM reference (aka pointer) */
class Reference
{
public:
void set_reference(Node elt);
Node get_reference();
std::string get_name();
std::string name;
XPath path;
Node ptr;
};
/** @internal
* RAM implementation of a node */
class RamNode : public NodePatron
{
public:
//////////////////////////////////////////////////////////
//// MODIFIERS ////
//////////////////////////////////////////////////////////
Node get_parent();
void add_children(const std::string &type, const std::vector<const MXml *> &lst);
unsigned int get_reference_count() const;
const Node get_reference_at(unsigned int i, std::string &name) const;
void set_reference(const std::string &name, Node e);
void set_reference(const std::string &name, const XPath &path);
XPath get_reference_path(const std::string &name);
///////////////////////////////////////////////////////////
///// Not const getter /////
///////////////////////////////////////////////////////////
unsigned long get_attribute_count() const;
Attribute *get_attribute_at(unsigned int i);
const Attribute *get_attribute_at(unsigned int i) const;
// GET CHILD, TYPE PRECISE
unsigned long get_children_count(const std::string &type) const;
Node get_child_at(const std::string &type, unsigned int i);
const Node get_child_at(const std::string &type, unsigned int i) const;
unsigned long get_children_count(int type) const;
Node get_child_at(int type, unsigned int i);
const Node get_child_at(int type, unsigned int i) const;
// MODIFY
Node add_child(const std::string sub_name);
void remove_child(Node child);
void on_event(const ChangeEvent &ce);
/////////////////////////////////////////////////////////////////
/// Constructors, copy operator ////
/////////////////////////////////////////////////////////////////
RamNode();
RamNode(NodeSchema *schema);
virtual ~RamNode();
void operator =(const RamNode &e);
//////////////////////////////////////////////////////////
//// A CLASSER ////
//////////////////////////////////////////////////////////
private:
// TODO: class children by type
class NodeCol
{
public:
std::string type;
std::deque<Node> nodes;
};
//std::deque<Node> children;
std::deque<NodeCol> children;
// Obsolete
std::deque<Reference> references;
std::deque<Attribute> attributes;
RamNode *parent;
/** To distinguish between the child of the same types */
std::string sub_type;
friend class Node;
};
/** @endcond */
}
}
#endif
| 5,626
|
C++
|
.h
| 141
| 36.801418
| 108
| 0.560958
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,026
|
serial-session.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/comm/serial-session.hpp
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef SERIAL_SESSION_HPP
#define SERIAL_SESSION_HPP
#include "comm/iostreams.hpp"
#include "cutil.hpp"
#include "slots.hpp"
#include "bytearray.hpp"
#include <stdint.h>
#include <queue>
#include "../journal.hpp"
namespace utils
{
namespace comm
{
using namespace utils;
// 500 ms seems to be too small, at least when debugging
#define COMM_DEFAULT_TIMEOUT 500
#define COMM_SESSION_DEFAULT_TIMEOUT 800
/** @brief Data packet container */
class Packet
{
public:
Packet();
Packet(uint8_t flags, uint32_t length);
Packet(uint32_t length);
~Packet();
Packet(const Packet &p);
void operator =(const Packet &p);
Packet operator +(const Packet &p);
std::string to_string() const;
/** @brief Data buffer pointer */
uint8_t *data;
/** @brief Data buffer length */
uint32_t length;
/** @brief Packet flags (8 bits) */
uint8_t flags;
};
/** @brief Dummy class to notify communication errors */
class ComError{};
/** @brief Enable small packets (<= 4 ko) exchange with:
* - CRC check
* - ACQ management / retries on failure, with packet counter.
* Un thread de plus (s�pa ack VS donn�es in) */
class DataLink:
public CProvider<Packet>, /* Provides received packets to higher layer */
public CProvider<ComError> /* Dispatch error notifications to higher layer */
{
public:
DataLink(IOStream *s, uint32_t max_packet_length = 2*8192);
~DataLink();
int put_packet(const Packet &pkt, uint16_t timeout = COMM_DEFAULT_TIMEOUT);
/** Start listening for input packets on the iostream */
int start();
private:
/** Already started listening on the iostream ? */
bool started;
void com_thread();
void client_thread();
int wait_ack(uint16_t packet_number, uint16_t timeout);
uint16_t ack_packet_number;
uint32_t max_packet_length;
IOStream *stream;
CRCStream cstream;
hal::Mutex mutex_ack, mutex_put;
hal::Signal signal_ack;
uint8_t *buffer;
uint16_t packet_counter;
static journal::Logable log;
bool do_terminate;
hal::Signal signal_terminated1, signal_terminated2;
hal::Fifo<Packet> packets;
enum dl_type_enum
{
DL_ACK = 0,
DL_NACK = 1,
DL_DATA = 2
};
hal::Mutex mutex_tx;
};
/** @brief Long packets segmentation. */
class Transport:
public CProvider<Packet>, /* Provides received packets to higher layer */
public CProvider<ComError>,/* Dispatch error notifications to higher layer */
private CListener<Packet>, /* Read packets from lower layer */
private CListener<ComError> /* Read error notifications from lower layer */
{
public:
Transport(DataLink *stream,
/** Max length of PDU packets in emission */
uint32_t tx_segmentation = 256,
/** Max length of reassembled packets in reception */
uint32_t max_packet_length = 1024*1024*4/*32*/);
virtual ~Transport();
int put_packet(const Packet &p, void (*notification)(float percent) = nullptr);
void on_event(const Packet &p);
void on_event(const ComError &ce);
private:
DataLink *stream;
uint32_t rx_buffer_offset, rx_buffer_length;
uint32_t max_packet_length, tx_segmentation;
uint8_t *buffer;
hal::Mutex mutex;
static journal::Logable log;
};
class CmdeFunctor
{
public:
virtual int call(model::ByteArray &data_in, model::ByteArray &data_out) = 0;
};
template <class A>
class SpecificCmdeFunctor: public CmdeFunctor
{
public:
SpecificCmdeFunctor(A *object, int(A::*m_function)(model::ByteArray &data_in, model::ByteArray &data_out))
{
this->object = object;
this->m_function = m_function;
}
virtual int call(model::ByteArray &data_in, model::ByteArray &data_out)
{
return (*object.*m_function)(data_in, data_out);
}
private:
int (A::*m_function)(model::ByteArray &, model::ByteArray &);
A *object;
};
/** @brief Une session, notions de :
* - Requ�te / r�ponse
* - n� de service
*/
class Session:
public CProvider<Packet>, /* Provides request packets to higher layer */
private CListener<Packet>, /* Read packets from lower layer */
private CListener<ComError>/* Read error notifications from lower layer */
{
public:
Session(Transport *device = nullptr, uint32_t max_buffer_size = 65536);
void set_transport(Transport *device);
~Session();
/** Transmit a read request to the remote pair */
int request(uint8_t service, uint8_t cmde, const model::ByteArray &data_in, model::ByteArray &data_out, uint32_t timeout = COMM_SESSION_DEFAULT_TIMEOUT, void (*notification)(float percent) = nullptr);
/** Transmit a write only request to the remote pair */
int request(uint8_t service, uint8_t cmde, const model::ByteArray &data_in, uint32_t timeout = COMM_SESSION_DEFAULT_TIMEOUT);
template<class A>
int register_cmde(uint8_t service,
uint8_t cmde,
A *target,
int (A:: *fun)(model::ByteArray &, model::ByteArray &));
int register_cmde(uint8_t service, uint8_t cmde, CmdeFunctor *functor);
private:
void client_thread();
int request(uint8_t service, uint8_t cmde, const Packet &data_in, Packet &data_out, uint32_t timeout = COMM_SESSION_DEFAULT_TIMEOUT, void (*notification)(float percent) = nullptr);
void on_event(const ComError &ce);
void on_event(const Packet &p);
bool session_error;
hal::Mutex mutex_data_in;
hal::Signal signal_data_in, signal_terminated;
std::queue<Packet> data_in;
uint32_t max_buffer_size;
Transport *tp;
hal::Mutex request_lock, response_lock;
hal::Signal signal_answer;
uint8_t service_waited;
uint32_t response_max_length, response_length;
Packet response;
int do_terminate;
/* For debug purpose */
static journal::Logable log;
class CmdeStorage
{
public:
uint8_t service;
uint8_t cmde;
CmdeFunctor *functor;
};
std::deque<CmdeStorage> cmde_handlers;
hal::Mutex mutex;
hal::Fifo<Packet> client_packets;
};
template<class A>
int Session::register_cmde(uint8_t service,
uint8_t code_cmde,
A *target,
int (A:: *fun)(model::ByteArray &, model::ByteArray &))
{
/* TODO: check if not already registered */
SpecificCmdeFunctor<A> *f = new SpecificCmdeFunctor<A>(target, fun);
CmdeStorage storage;
storage.service = service;
storage.cmde = code_cmde;
storage.functor = f;
cmde_handlers.push_back(storage);
return 0;
}
}
}
#endif
| 7,168
|
C++
|
.h
| 214
| 30.042056
| 202
| 0.704042
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,027
|
serial.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/comm/serial.hpp
|
/**
* This file is part of LIBSERIAL.
*
* LIBSERIAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBSERIAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBSERIAL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef SERIAL_H
#define SERIAL_H
#include "comm/iostreams.hpp"
#include "cutil.hpp"
#include <stdint.h>
#include <stdio.h>
#include "../journal.hpp"
#ifdef WIN
#include <windows.h>
#endif
#include <string>
namespace utils
{
namespace comm
{
using namespace utils;
class EscapedIOStream : public IOStream
{
public:
EscapedIOStream(IOStream *c);
void putc(char c);
int getc(int timeout = 0);
void start_frame();
void end_frame();
int get_frame(char *buffer, unsigned int max_len);
virtual void discard_rx_buffer(){compo->discard_rx_buffer();}
private:
IOStream *compo;
unsigned short tx_crc;
};
class SerialInfo
{
public:
std::string name;
std::string complete_name;
std::string techno;
};
typedef enum serial_parity_enum
{
PAR_NONE,
PAR_ODD,
PAR_EVEN
} serial_parity_t;
class Serial : public IOStream
{
public:
static int enumerate(std::vector<SerialInfo> &infos);
Serial();
virtual ~Serial();
/** @returns 0 si ok, sinon code d'erreur */
int connect(std::string port_name = "COM1", int baudrate = 115200,
serial_parity_t parity = PAR_NONE);
virtual void putc(char c);
virtual int getc(int timeout = 0);
virtual void discard_rx_buffer(){}
int get_nb_bytes_available();
void disconnect();
bool is_connected();
void set_timeout(int tm);
protected:
std::string port_name;
int baudrate;
serial_parity_t parity;
# ifdef WIN
HANDLE serial_handle;
# endif
bool connected;
};
#define FD_BUFFER_SIZE (128*1024)
class FDSerial : public IOStream
{
public:
FDSerial();
virtual ~FDSerial();
virtual void putc(char c);
virtual int getc(int timeout = 0);
//virtual int read(uint8_t *buffer, uint32_t length, int timeout);
/** @returns 0 si ok, sinon code d'erreur */
int connect(std::string port_name = "COM2",
int baudrate = 115200,
serial_parity_t parity = PAR_NONE,
bool flow_control = false);
void disconnect();
bool is_connected();
virtual void discard_rx_buffer();
unsigned int nb_rx_available();
void flush();
void debloquer_reception();
private:
void com_thread(void);
hal::Mutex mutex_input, mutex_output;
hal::Signal hevt_stop, signal_debloquer_reception;
hal::Signal hevt_write, hevt_tx_done;
hal::Signal hevt_rx_available;
hal::Signal hevt_tx_available, hevt_tx_space_available, hevt_start, hevt_stopped, hevt_connection;
# ifdef WIN
OVERLAPPED ov;
HANDLE hfile;
# endif
char *input_buffer;
uint32_t input_buffer_offset, input_buffer_size;
char *output_buffer;
uint32_t output_buffer_offset, output_buffer_size;
bool serial_is_connected;
uint32_t nb_bytes_waited;
};
class SerialConfig
{
public:
SerialConfig(){port="COM1";baud_rate=115200;}
std::string port;
int baud_rate;
void dump();
};
}
}
#endif
| 3,567
|
C++
|
.h
| 135
| 23.688889
| 100
| 0.722729
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,028
|
iostreams.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/comm/iostreams.hpp
|
#ifndef IOSTREAMS_HPP
#define IOSTREAMS_HPP
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#include "bytearray.hpp"
//#include <stdio.h>
#include <string>
#ifdef putc
#undef putc
#endif
namespace utils
{
/** @brief Protocols and communication interfaces */
namespace comm
{
/** @brief Abstract input stream interface */
class InputStream
{
public:
virtual int getc(int timeout = 0) = 0;
unsigned short getw();
void get_data(char *buffer, int len);
/** @brief Read a line of (text) data from the stream.
* The line must be terminated by '\n'
* @param[out] res The line of text readen, '\n' caracter not included.
* @param timeout Timeout in milliseconds;
* @returns -1 if timeout occured */
int get_line(std::string &res, int timeout);
/** @return number of bytes read */
virtual int read(uint8_t *buffer, uint32_t length, int timeout);
int read(model::ByteArray &ba, uint32_t length, int timeout);
virtual void discard_rx_buffer();
// Débloque un appelant de la fonction read
virtual void debloquer_reception() {}
protected:
private:
};
/** @brief Abstract output stream interface */
class OutputStream
{
public:
virtual void write(const uint8_t *buffer, uint32_t len);
virtual void putc(char c) = 0;
void put(const model::ByteArray &ba);
void put_data(const void *buffer, int len);
void put_string(std::string s);
void putw(unsigned short s);
virtual void flush(){}
protected:
private:
};
class IOStream : public InputStream, public OutputStream
{
};
class CRCStream: public IOStream
{
public:
CRCStream(IOStream *stream);
virtual void putc(char c);
void start_tx();
void flush();
void write(const uint8_t *buffer, uint32_t len);
virtual int read(uint8_t *buffer, uint32_t length, int timeout);
virtual int getc(int timeout);
void start_rx();
int check_crc();
uint16_t get_current_tx_crc();
private:
IOStream *stream;
uint16_t current_tx_crc;
uint16_t current_rx_crc;
};
}
}
#endif
| 2,684
|
C++
|
.h
| 91
| 27.230769
| 79
| 0.731413
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,029
|
crc.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/comm/crc.hpp
|
#ifndef CRC_H
#define CRC_H
#include <stdint.h>
namespace utils
{
namespace comm
{
extern bool crc_check(char *b, uint32_t size);
extern unsigned short crc_calc(char *b, uint32_t size);
extern unsigned short crc_update(unsigned short crc, char data);
}
}
#endif
| 271
|
C++
|
.h
| 13
| 19.230769
| 64
| 0.776
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,030
|
socket.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/comm/socket.hpp
|
#ifndef SOCKET_HPP
#define SOCKET_HPP
#ifdef WIN
#include <winsock2.h>
#endif
#include "comm/iostreams.hpp"
#include "../journal.hpp"
#include "slots.hpp"
#include "cutil.hpp"
#include <string>
#include <stdint.h>
#ifdef WIN
#include "winsock2.h"
#elif defined(LINUX)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> /* close */
#include <netdb.h> /* gethostbyname */
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
typedef struct in_addr IN_ADDR;
#endif
namespace utils
{
namespace comm
{
using namespace utils;
class Socket;
class BluetoothServer;
class BluetoothClient;
struct SocketClosedEvent
{
Socket *socket;
};
struct SocketOpenedEvent
{
Socket *socket;
};
extern int send_udp_packet(const std::string &host,
uint16_t port,
utils::model::ByteArray &data);
struct UDPPacket
{
utils::model::ByteArray data;
std::string ip_address;
};
class UDPListener: public CProvider<UDPPacket>
{
public:
UDPListener();
int listen(uint16_t port, uint32_t mps = 4096);
~UDPListener();
private:
bool listening;
/* our socket */
int fd;
uint8_t *buf;
uint32_t mps;
journal::Logable log;
void thread_entry();
};
class Socket: public IOStream,
public CProvider<SocketClosedEvent>
{
public:
typedef enum socket_type_enum
{
SOCKET_UDP = 0,
SOCKET_TCP = 1,
SOCKET_BT = 2
} socket_type_t;
Socket();
virtual ~Socket();
bool is_connected() const;
int connect(std::string target_ip,
uint16_t target_port,
socket_type_t type = SOCKET_TCP);
int disconnect();
void write(const uint8_t *buffer, uint32_t len);
int read(uint8_t *buffer, uint32_t length, int timeout);
int getc(int timeout = 0);
void putc(char c);
void flush();
int get_nb_rx_available();
uint16_t get_local_port() const;
uint16_t get_remote_port() const;
std::string get_remote_ip() const;
friend class SocketServer;
friend class BluetoothServer;
friend class BluetoothClient;
private:
journal::Logable log;
void rx_thread();
hal::RawFifo rx_fifo;
socket_type_t socket_type;
uint16_t local_port, remote_port;
std::string remote_ip;
bool connected;
SOCKET sock;
fd_set read_fs, write_fs;
# ifdef WIN
# else
# endif
};
class SocketServer: public CProvider<SocketOpenedEvent>
{
public:
SocketServer();
~SocketServer();
/** Open a server port and listen for clients */
int listen(uint16_t port, Socket::socket_type_t type = Socket::SOCKET_TCP);
/** Stop listening for new clients */
void stop();
private:
void thread_handler();
journal::Logable log;
SOCKET listen_socket;
sockaddr_in service;
# ifdef WIN
WSAData wsa;
# endif
uint32_t local_port;
Socket::socket_type_t socket_type;
int listening;
hal::Signal thread_finished;
};
class BluetoothServer: private journal::Logable,
public CProvider<SocketOpenedEvent>
{
public:
BluetoothServer(const std::string &service_name,
const std::string &comment);
/** Open a server port and listen for clients
* @returns:
* 0 ok
* -255 Not supported on this target
* -254 blue.dll not found
* -253 Routine not found in blue.dll (invalid DLL)
* -3 No bluetooth hardware on the host target (bind error)
* -6 Register bt service failed
**/
int listen();
/** Stop listening for new clients */
void stop();
private:
void thread_handler();
SOCKET listen_socket;
std::string service_name;
std::string comment;
};
class BluetoothClient: private journal::Logable
{
public:
BluetoothClient();
~BluetoothClient();
int connect(const model::ByteArray &target_mac, Socket **socket);
private:
};
#if 0
class BluetoothSocket: private journal::Logable,
public IOStream
{
public:
BluetoothSocket(){}
/** Open a server port and listen for clients */
int listen();
/** Stop listening for new clients */
void stop();
bool is_connected();
int connect(std::string target_mac);
int disconnect();
void write(const uint8_t *buffer, uint32_t len);
int read(uint8_t *buffer, uint32_t length, int timeout);
int getc(int timeout = 0);
void putc(char c);
private:
void thread_handler();
SOCKET listen_socket;
sockaddr_in service;
WSAData wsa;
uint32_t local_port;
Socket::socket_type_t socket_type;
};
#endif
}
}
#endif
| 4,596
|
C++
|
.h
| 193
| 20.678756
| 77
| 0.706165
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,031
|
stdview-fields.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/stdview-fields.hpp
|
#ifndef STDVIEW_FIELDS_H
#define STDVIEW_FIELDS_H
#include "mmi/stdview.hpp"
#include "comm/serial.hpp"
namespace utils
{
namespace mmi
{
namespace fields
{
class VueDecimal: public AttributeView
{
public:
VueDecimal(Attribute *model, int compatibility_mode = 0);
virtual ~VueDecimal() {}
bool is_valid();
void set_sensitive(bool b);
// Deprecated
unsigned int get_nb_widgets();
// Deprecated
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void update_valid();
void on_event(const ChangeEvent &ce);
void on_signal_changed();
bool on_signal_focus_out(GdkEventFocus *gef);
Gtk::SpinButton spin;
Gtk::Label label, label_unit;
Gtk::Alignment align;
Gtk::HBox hbox;
bool is_sensitive;
bool valid;
};
class VueFloat: public AttributeView
{
public:
VueFloat(Attribute *model, Node modele_vue);
VueFloat(Attribute *model);
void init(Attribute *model, Node modele_vue);
virtual ~VueFloat() {
}
void set_sensitive(bool b);
// Deprecated
unsigned int get_nb_widgets();
// Deprecated
Gtk::Widget *get_widget(int index);
void update_langue();
Gtk::Widget *get_gtk_widget();
private:
void on_event(const ChangeEvent &ce);
void on_signal_changed();
Gtk::SpinButton spin;
Gtk::Label label, label_unit;
utils::model::Localized valeur_label;
};
class VueChaine: public AttributeView
{
public:
VueChaine(Attribute *model, bool small_ = false);
virtual ~VueChaine();
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
void update_langue();
bool is_valid();
Gtk::Widget *get_gtk_widget();
private:
bool valid;
void on_event(const ChangeEvent &ce);
void on_signal_changed();
void update_valid();
Gtk::Label label, label_unit;
Gtk::Entry entry;
};
class VueChaineConstante: public AttributeView
{
public:
VueChaineConstante(Attribute *model);
virtual ~VueChaineConstante()
{
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
void update_langue();
bool is_valid();
Gtk::Widget *get_gtk_widget();
private:
bool valid;
void on_event(const ChangeEvent &ce);
//void on_signal_changed();
void update_valid();
Gtk::Label label, label_unit;
Gtk::Label entry;
};
class VueTexte: public AttributeView {
public:
VueTexte(Attribute *model, bool small_);
virtual ~VueTexte() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
void update_langue();
Gtk::Widget *get_gtk_widget();
private:
void on_event(const ChangeEvent &ce);
void on_signal_changed();
Gtk::Label label;
Gtk::TextView view;
Gtk::ScrolledWindow scroll;
Gtk::Frame frame;
};
class VueDossier: public AttributeView {
public:
VueDossier(Attribute *model);
virtual ~VueDossier() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
void update_langue();
Gtk::Widget *get_gtk_widget();
private:
bool on_focus_in(GdkEventFocus *gef);
bool on_frame_event(GdkEvent *gef);
void on_event(const ChangeEvent &ce);
void on_folder_changed();
Gtk::Label label;
Gtk::FileChooserButton *bouton;
Gtk::FileChooserDialog *fcd;
};
class VueFichier: public AttributeView
{
public:
VueFichier(Attribute *model, bool fichier_existant = true);
virtual ~VueFichier();
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void maj_langue();
private:
bool fichier_existant;
class BoutonFichier: public Gtk::Button//Gtk::FileChooserButton
{
public:
BoutonFichier(Gtk::FileChooserDialog *fcd, VueFichier *parent);
private:
void gere_clic();
//bool on_button_press_event(GdkEventButton* event);
Gtk::FileChooserDialog *fcd;
VueFichier *parent;
};
bool gere_bouton(GdkEventButton *non_ut);
void maj_chemin(const std::string &s);
bool on_focus_in(GdkEventFocus *gef);
bool on_frame_event(GdkEvent *gef);
void on_event(const ChangeEvent &ce);
void gere_changement_fichier();
Gtk::Label label;
BoutonFichier *bouton;
Gtk::FileChooserDialog *fcd;
friend class BoutonFichier;
};
class VueHexa: public AttributeView {
public:
VueHexa(Attribute *model);
virtual ~VueHexa() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_signal_changed();
Gtk::Label label, label_unit;
Gtk::Entry entry;
bool valid;
};
class VueOctets: public AttributeView {
public:
VueOctets(Attribute *model);
virtual ~VueOctets() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_signal_changed();
Gtk::Label label, label_unit;
Gtk::Entry entry;
bool valid;
};
class VueBouleen: public AttributeView
{
public:
VueBouleen(Attribute *model, bool affiche_label = true);
virtual ~VueBouleen();
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_signal_toggled();
Gtk::Label label, lab;
Gtk::CheckButton check;
bool lock;
};
class VueLed: public AttributeView
{
public:
VueLed(Attribute *model, bool editable = true, bool error = false);
virtual ~VueLed();
void set_readonly(bool b);
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_signal_toggled(const LedEvent &le);
Gtk::Label label, lab;
GtkLed led;
Gtk::HBox vbox;
Gtk::Alignment align;
bool lock;
bool editable;
};
class VueCombo: public AttributeView {
public:
VueCombo(Attribute *model);
virtual ~VueCombo() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_combo_changed();
Gtk::Label label;
Gtk::ComboBox combo;
class ModelColumns: public Gtk::TreeModel::ColumnRecord {
public:
ModelColumns() {
add(m_col_name);
add(m_col_real_name);
add(m_col_unit);
}
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Glib::ustring> m_col_unit;
Gtk::TreeModelColumn<Glib::ustring> m_col_real_name;
};
ModelColumns columns;
Glib::RefPtr<Gtk::ListStore> tree_model;
};
class VueSelPortCOM: public AttributeView {
public:
VueSelPortCOM(Attribute *model);
virtual ~VueSelPortCOM() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
std::vector<comm::SerialInfo> serials;
void on_event(const ChangeEvent &ce);
void on_combo_changed();
Gtk::Label label;
Gtk::ComboBox combo;
class ModelColumns: public Gtk::TreeModel::ColumnRecord {
public:
ModelColumns() {
add(m_col_name);
add(m_col_real_name);
add(m_col_unit);
}
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Glib::ustring> m_col_unit;
Gtk::TreeModelColumn<Glib::ustring> m_col_real_name;
};
ModelColumns columns;
Glib::RefPtr<Gtk::ListStore> tree_model;
};
class VueChoixCouleur: public AttributeView {
public:
VueChoixCouleur(Attribute *model);
virtual ~VueChoixCouleur() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_color_changed();
Gtk::Label label;
Gtk::ColorButton color;
ColorButton *cb;
};
class VueDate: public AttributeView {
public:
VueDate(Attribute *model);
virtual ~VueDate() {
}
void set_sensitive(bool b);
unsigned int get_nb_widgets();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
void update_langue();
private:
void on_event(const ChangeEvent &ce);
void on_date_changed();
bool on_signal_focus_out(GdkEventFocus *gef);
Gtk::Label label;
Gtk::HBox hbox;
Gtk::Alignment a_month;
Glib::RefPtr<Gtk::Adjustment> adj_year, adj_month, adj_day;
Gtk::SpinButton year, month, day;
bool valid;
};
class VueChoix: public AttributeView, private CListener<KeyPosChangeEvent> {
public:
VueChoix(Attribute *model, Node parent, NodeViewConfiguration config);
virtual ~VueChoix();
void update_langue();
Gtk::Widget *get_widget(int index);
Gtk::Widget *get_gtk_widget();
unsigned int get_nb_widgets();
void set_sensitive(bool b);
bool is_valid();
private:
void on_event(const KeyPosChangeEvent &kpce) {
CProvider < KeyPosChangeEvent > ::dispatch(kpce);
}
void update_sub_view();
void on_event(const ChangeEvent &ce);
void on_radio_activate(unsigned int num);
Gtk::RadioButton **radios;
Gtk::RadioButton::Group group;
unsigned int nb_choices;
Gtk::VBox vbox;
JFrame frame;
NodeView *current_view;
Node model_parent;
NodeViewConfiguration config;
};
}
}
}
#endif
| 9,511
|
C++
|
.h
| 366
| 23.128415
| 76
| 0.725592
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,032
|
stdview.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/stdview.hpp
|
#ifndef STDVIEW_HPP
#define STDVIEW_HPP
/** @file stdview.hpp
*
* Standard element editor (using schemas)
*
* (C) J A 2008-2009 */
#include "../journal.hpp"
#include "modele.hpp"
#include "cutil.hpp"
#include "mmi/gtkutil.hpp"
namespace utils
{
/** @brief Generic view (MMI) generation */
namespace mmi
{
using namespace model;
class Controleur
{
public:
// Get dynamic content at the specified path in the view model
virtual std::string genere_contenu_dynamique(const std::string &action_path,
Node node,
Gtk::Widget **widget) {*widget = nullptr; return "";}
virtual void gere_action(const std::string &action, Node node) = 0;
};
class VueGenerique;
class FabriqueWidget
{
public:
virtual VueGenerique *fabrique(Node modele_donnees, Node modele_vue, Controleur *controleur) = 0;
};
class VueGenerique
{
public:
static VueGenerique *fabrique(Node modele_donnees, Node modele_vue, Controleur *controleur = nullptr);
static int enregistre_widget(std::string id, FabriqueWidget *frabrique);
virtual Gtk::Widget *get_gtk_widget() = 0;
VueGenerique();
virtual ~VueGenerique();
// Demande de regénération récursive du contenu dynamique (géré par l'utilisateur)
virtual void maj_contenu_dynamique();
virtual void set_sensitive(bool sensitive);
typedef enum widget_type_enum
{
/** Automatic widget type determination according to the model schema */
WIDGET_AUTO = 0,
WIDGET_NULL,
WIDGET_FIELD,
WIDGET_FIELD_LIST,
WIDGET_FIXED_STRING,
WIDGET_BUTTON,
WIDGET_BORDER_LAYOUT,
WIDGET_GRID_LAYOUT,
WIDGET_FIXED_LAYOUT,
WIDGET_TRIG_LAYOUT,
WIDGET_NOTEBOOK,
WIDGET_PANNEAU, // ?
WIDGET_IMAGE,
WIDGET_LABEL,
WIDGET_COMBO,
WIDGET_DECIMAL_ENTRY,
WIDGET_HEXA_ENTRY,
WIDGET_FLOAT_ENTRY,
WIDGET_RADIO,
WIDGET_SWITCH,
WIDGET_CADRE,
WIDGET_CHOICE,
WIDGET_BYTES,
WIDGET_TEXT,
WIDGET_STRING,
WIDGET_COLOR,
WIDGET_DATE,
WIDGET_FOLDER,
WIDGET_FILE,
WIDGET_SERIAL,
WIDGET_LIST_LAYOUT,
WIDGET_VBOX,
WIDGET_HBOX,
WIDGET_BUTTON_BOX,
WIDGET_VUE_SPECIALE,
WIDGET_SEP_H,
WIDGET_SEP_V,
WIDGET_TABLE,
WIDGET_LED,
WIDGET_INVALIDE
} WidgetType;
static const unsigned int WIDGET_MAX = ((int) WIDGET_INVALIDE);
static WidgetType desc_vers_type(const std::string &s);
static std::string type_vers_desc(WidgetType type);
Node modele_donnees;
Node modele_vue;
private:
protected:
std::vector<VueGenerique *> enfants;
bool is_sensitive;
Controleur *controleur;
};
class SubPlot: public VueGenerique
{
public:
SubPlot(Node &data_model, Node &view_model, Controleur *controler);
Gtk::Widget *get_gtk_widget();
private:
Gtk::Grid grille;
};
class TrigLayout: public VueGenerique
{
public:
TrigLayout(Node &data_model, Node &view_model);
Gtk::Widget *get_gtk_widget();
private:
Gtk::VBox vbox;
Gtk::HPaned hpane;
Gtk::VSeparator vsep;
};
class VueCadre: public VueGenerique
{
public:
VueCadre(Node &data_model, Node &view_model, Controleur *controler);
Gtk::Widget *get_gtk_widget();
~VueCadre();
private:
Gtk::Frame cadre;
};
class VueLineaire: public VueGenerique
{
public:
VueLineaire(int vertical, Node &data_model, Node &view_model, Controleur *controler);
Gtk::Widget *get_gtk_widget();
~VueLineaire();
private:
int vertical;
Gtk::Box *box;
Gtk::VBox vbox;
Gtk::HBox hbox;
};
class NoteBookLayout: public VueGenerique
{
public:
NoteBookLayout(Node &data_model, Node &view_model, Controleur *controler);
Gtk::Widget *get_gtk_widget();
~NoteBookLayout();
private:
Gtk::Notebook notebook;
};
class HButtonBox: public VueGenerique
{
public:
HButtonBox(Node &data_model, Node &view_model, Controleur *controler = nullptr);
Gtk::Widget *get_gtk_widget();
private:
utils::model::Node data_model, view_model;
Controleur *controler;
Gtk::HButtonBox hbox;
struct Action
{
std::string name;
Gtk::Button *button;
bool need_sel;
bool is_default;
};
std::vector<Action> actions;
void on_button(std::string action);
};
class CustomWidget: public VueGenerique
{
public:
CustomWidget(Node &data_model, Node &view_model, Controleur *controler = nullptr);
Gtk::Widget *get_gtk_widget();
private:
// Demande de regénération récursive du contenu dynamique (géré par l'utilisateur)
void maj_contenu_dynamique();
Node data_model, view_model;
Controleur *controler;
std::string id;
Gtk::EventBox evt_box;
Gtk::Widget *widget;
};
class ListLayout:
public VueGenerique,
private CListener<ChangeEvent>
{
public:
ListLayout(Node &data_model, Node &view_model, Controleur *controler = nullptr);
~ListLayout();
Gtk::Widget *get_gtk_widget();
private:
void maj_contenu_dynamique();
void on_event(const ChangeEvent &ce);
Node get_selection();
void rebuild_view();
void update_view();
void on_button(std::string action);
void on_click(const LabelClick &path);
int current_selection;
Controleur *controler;
Gtk::VBox vbox, vbox_ext;
Gtk::Table table;
Gtk::VSeparator vsep;
Gtk::HButtonBox hbox;
struct Elem
{
Node model;
int id;
Gtk::VBox *vbox;
Gtk::Widget *widget;
SensitiveLabel *label;
Gtk::Frame *frame;
Gtk::Alignment *align, *align2;
Gtk::EventBox *evt_box;
};
bool on_button_press_event(GdkEventButton *evt, Elem *elt);
std::vector<Elem> elems;
struct Action
{
std::string name;
Gtk::Button *button;
bool need_sel;
bool is_default;
};
std::vector<Action> actions;
Gtk::ScrolledWindow scroll;
};
class NodeViewConfiguration
{
public:
NodeViewConfiguration();
/** Display attribute descriptions */
bool show_desc;
/** Display element descriptions */
bool show_main_desc;
/** Display children in a tree view */
bool show_children;
/** Small strings fields */
bool small_strings;
/** Display a separator between attributes */
bool show_separator;
/** Number of columns */
int nb_columns;
/** Disable view of all children, even if optionnals, etc. */
bool disable_all_children;
/** Display only a tree view, without a view to edit contents */
bool display_only_tree;
bool expand_all;
int nb_attributes_by_column;
/** Horizontally split internal view if needed (otherwise vertically) */
bool horizontal_splitting;
int table_width, table_height;
std::string to_string() const;
};
class KeyPosChangeEvent
{
public:
std::vector<std::string> vchars;
};
class VueTable
: private CListener<ChangeEvent>,
public VueGenerique
{
public:
struct Config
{
bool affiche_boutons;
Config(){affiche_boutons = true;}
};
VueTable(Node &modele_donnees, Node &modele_vue, Controleur *controleur);
VueTable(Node model, NodeSchema *&sub, const NodeViewConfiguration &cfg);
void init(Node model, NodeSchema *&sub, const NodeViewConfiguration &cfg, Config &config);
Gtk::Widget *get_gtk_widget();
private:
Config config;
Node model;
int nb_lignes;
NodeSchema *schema;
bool lock;
SubSchema sub_schema;
bool can_remove;
bool is_valid();
void update_langue();
void update_view();
void clear_table();
void on_selection_changed();
Node get_selected();
void set_selection(Node sub);
void on_editing_done(Glib::ustring path, Glib::ustring text, std::string col);
void on_editing_start(Gtk::CellEditable *ed, Glib::ustring path, std::string col);
void on_b_remove();
void on_b_up();
void on_b_down();
void on_b_add();
void on_b_command(std::string command);
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns(){}
Gtk::TreeModelColumn<Glib::ustring> m_cols[30];
Gtk::TreeModelColumn<Node> m_col_ptr;
};
class MyTreeView: public Gtk::TreeView
{
public:
MyTreeView(VueTable *parent);
virtual bool on_button_press_event(GdkEventButton *ev);
private:
VueTable *parent;
};
Gtk::ScrolledWindow scroll;
MyTreeView tree_view;
Glib::RefPtr<Gtk::TreeStore> tree_model;
ModelColumns columns;
Gtk::VButtonBox button_box;
Gtk::Button b_add;
Gtk::Button b_remove, b_up, b_down;
Gtk::HBox hbox;
std::vector<Gtk::CellRenderer *> cell_renderers;
void on_event(const ChangeEvent &ce);
void maj_cellule(Gtk::TreeModel::Row &trow, unsigned int col, unsigned int row);
void maj_ligne(Gtk::TreeModel::Row &trow, unsigned int row);
};
class AttributeListView;
class FocusInEvent{};
class AttributeView: private CListener<ChangeEvent>,
public CProvider<FocusInEvent>,
public CProvider<KeyPosChangeEvent>,
public VueGenerique
{
public:
static AttributeView *factory(Node model, Node view);
static AttributeView *build_attribute_view(Attribute *model,
const NodeViewConfiguration &config,
Node parent);
virtual ~AttributeView();
virtual unsigned int get_nb_widgets() = 0;
virtual Gtk::Widget *get_widget(int index) = 0;
virtual void set_sensitive(bool b) = 0;
virtual void set_readonly(bool b) {}
virtual void update_langue() {}
virtual void maj_langue() {update_langue();}
virtual bool is_valid();
bool on_focus_in(GdkEventFocus *gef);
protected:
Attribute *model;
std::string tp;
virtual void on_event(const ChangeEvent &ce) = 0;
bool lock;
friend class AttributeListView;
private:
/** Choose the best appropriate view type for the given attribute schema */
static VueGenerique::WidgetType choose_view_type(refptr<AttributeSchema> as, bool editable = true);
};
class VueListeChamps: public VueGenerique,
private CListener<ChangeEvent>,
private CListener<FocusInEvent>,
public CProvider<FocusInEvent>,
public CProvider<KeyPosChangeEvent>,
private CListener<KeyPosChangeEvent>
{
public:
VueListeChamps(Node &data_model, Node &view_model, Controleur *controler = nullptr);
Gtk::Widget *get_gtk_widget();
~VueListeChamps();
void set_sensitive(bool sensitive);
private:
void on_event(const KeyPosChangeEvent &kpce){CProvider<KeyPosChangeEvent>::dispatch(kpce);}
void on_event(const FocusInEvent &fie){CProvider<FocusInEvent>::dispatch(fie);}
void on_event(const ChangeEvent &ce);
void update_langue();
Gtk::Table table;
struct ChampsCtx
{
Gtk::Label label, label_unit;
Gtk::Alignment align[3];
AttributeView *av;
};
std::vector<ChampsCtx *> champs;
};
class AttributeListView: public Gtk::VBox,
private CListener<ChangeEvent>,
private CListener<FocusInEvent>,
public CProvider<FocusInEvent>,
public CProvider<KeyPosChangeEvent>,
private CListener<KeyPosChangeEvent>
{
public:
AttributeListView();
void init(Node model,
const NodeViewConfiguration &config);
AttributeListView(Node model,
const NodeViewConfiguration &config);
~AttributeListView();
void update_langue();
bool is_valid();
void set_sensitive(bool sensitive);
bool has_atts, has_indics, has_commands;
private:
void on_event(const KeyPosChangeEvent &kpce){CProvider<KeyPosChangeEvent>::dispatch(kpce);}
void on_event(const FocusInEvent &fie){CProvider<FocusInEvent>::dispatch(fie);}
void on_the_realisation();
void on_event(const ChangeEvent &ce);
void on_b_command(std::string name);
Gtk::ScrolledWindow scroll;
Gtk::VBox the_vbox;
NodeViewConfiguration config;
Node model;
bool show_desc;
bool small_strings;
bool show_separator;
int nb_columns;
Gtk::Table table1, table2;
Gtk::VSeparator separator;
struct ViewElem
{
AttributeView *av;
Gtk::Label *desc;
};
std::vector<ViewElem> attributes_view;
bool list_is_sensitive;
Gtk::Table table_indicators;
Gtk::HButtonBox box_actions;
Gtk::HBox hbox;
JFrame frame_att, frame_indicators, frame_actions;
Gtk::Label label_desc;
std::vector<Gtk::Button *> buttons;
std::string class_name() const {return "AttributeListView";}
};
class SelectionView
: public JFrame,
private CListener<ChangeEvent>
{
public:
SelectionView();
SelectionView(Node model);
void setup(Node model);
private:
void init();
void update_view();
void clear_table();
void on_selection_changed();
NodeSchema *get_selected();
std::string class_name() const {return "SelectionView";}
void on_event(const ChangeEvent &pce){update_view();}
void set_selection(NodeSchema *&option);
void on_cell_toggled(const Glib::ustring& path);
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns(){add(m_col_use); add(m_col_name); add(m_col_ptr); add(m_col_desc);}
Gtk::TreeModelColumn<bool> m_col_use;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<NodeSchema *> m_col_ptr;
Gtk::TreeModelColumn<Glib::ustring> m_col_desc;
};
Node model;
bool lock;
Gtk::ScrolledWindow scroll;
Gtk::TreeView tree_view;
Glib::RefPtr<Gtk::TreeStore> tree_model;
ModelColumns columns;
};
class EVSelectionChangeEvent
{
public:
Node selection;
};
class NodeView: private CListener<ChangeEvent>,
public CProvider<EVSelectionChangeEvent>,
private CListener<KeyPosChangeEvent>,
public CProvider<KeyPosChangeEvent>,
public VueGenerique
{
public:
NodeView();
NodeView(Node model);
NodeView(Gtk::Window *mainWin, Node model);
NodeView(Gtk::Window *mainWin, Node model,
const NodeViewConfiguration &config);
int init(Node modele, const NodeViewConfiguration &config = NodeViewConfiguration(), Gtk::Window *mainWin = nullptr);
~NodeView();
Gtk::Widget *get_gtk_widget(){return get_widget();}
Gtk::Widget *get_widget();
void update_langue();
void set_sensitive(bool sensitive);
bool is_valid();
void set_selection(Node reg);
void maj_langue();
static std::string mk_label(const Localized &l);
static std::string mk_label_colon(const Localized &l);
protected:
private:
int init(Gtk::Window *mainWin,
Node model,
const NodeViewConfiguration &config);
NodeViewConfiguration config;
int nb_columns;
bool small_strings;
int affichage;
bool only_attributes;
bool show_children;
bool has_attributes;
Gtk::Window *mainWin;
bool show_separator;
bool has_optionnals;
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_name); add(m_col_ptr); add(m_col_pic);}
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Node> m_col_ptr;
Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > m_col_pic;
};
std::deque<std::pair<Glib::RefPtr<Gdk::Pixbuf>, NodeSchema *> > pics;
std::deque<NodeSchema *> pics_done;
Glib::RefPtr<Gdk::Pixbuf> get_pics(NodeSchema *&schema);
bool has_pic(NodeSchema *&schema);
void load_pics(NodeSchema *&sc);
void on_event(const ChangeEvent &ce);
std::string class_name() const {return "NodeView";}
virtual void on_treeview_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column);
class MyTreeView : public Gtk::TreeView
{
public:
MyTreeView();
void init(NodeView *parent);
MyTreeView(NodeView *parent);
virtual bool on_button_press_event(GdkEventButton *ev);
private:
NodeView *parent;
};
class MyTreeModel: public Gtk::TreeStore
{
public:
MyTreeModel(NodeView *parent, ModelColumns *cols);
protected:
virtual bool row_draggable_vfunc(const Gtk::TreeModel::Path& path) const;
virtual bool row_drop_possible_vfunc(const Gtk::TreeModel::Path& dest, const Gtk::SelectionData& selection_data) const;
virtual bool drag_data_received_vfunc( const TreeModel::Path& dest,
const Gtk::SelectionData& selection_data);
private:
NodeView *parent;
ModelColumns *cols;
};
void populate();
void populate(Node m, Gtk::TreeModel::Row row);
virtual void on_selection_changed();
Node get_selection();
void remove_element(Node elt);
void on_event(const KeyPosChangeEvent &kpce);
void add_element(std::pair<Node, SubSchema *>);
int set_selection(Gtk::TreeModel::Row &root, Node reg, std::string path);
void setup_row_view(Node ptr);
void populate_notebook();
void on_down(Node child);
void on_up(Node child);
bool lock;
NodeSchema *schema;
Node model;
AttributeListView table;
Gtk::HBox hbox;
Gtk::Notebook notebook;
JFrame frame_attributs;
bool show_desc;
Gtk::Label label_description;
Gtk::VBox vbox;
Gtk::HPaned hpane;
Gtk::ScrolledWindow scroll;
ModelColumns columns;
Glib::RefPtr<Gtk::TreeStore> tree_model;
Gtk::Menu popup_menu;
MyTreeView tree_view;
JFrame tree_frame, properties_frame;
NodeView *rp;
SelectionView *option_view;
std::vector<NodeView *> sub_views;
};
class NodeChangeEvent
{
public:
Node source;
};
class NodeDialog: private CListener<ChangeEvent>,
public CProvider<NodeChangeEvent>,
private CListener<KeyPosChangeEvent>,
public DialogManager::Placable
{
public:
void force_scroll(int dx, int dy);
void unforce_scroll();
/** @returns 0 -> ok, -1 : cancel */
static int display_modal(Node model, bool fullscreen = false, Gtk::Window *parent_window = nullptr);
static NodeDialog *display(Node model);
~NodeDialog();
void maj_langue();
private:
void on_event(const KeyPosChangeEvent &kpce);
void on_event(const ChangeEvent &ce);
NodeDialog(Node model, bool modal, Gtk::Window *parent_window = nullptr);
void on_b_close();
void on_b_apply();
void on_b_valid();
void update_view();
bool on_focus_in(GdkEventFocus *gef);
bool on_focus_out(GdkEventFocus *gef);
Gtk::Window *get_window();
bool on_expose_event2(const Cairo::RefPtr<Cairo::Context> &cr);
void remove_widgets();
void add_widgets();
Gtk::Window *window;
Gtk::Box *vb;
Node model;
Node backup;
bool lock, u2date;
Gtk::VBox vbox;
NodeView *ev;
Gtk::HButtonBox hbox;
Gtk::Button b_close;
Gtk::Button b_apply, b_valid;
Gtk::Toolbar toolbar;
Gtk::ToolButton tool_valid, tool_cancel;
Gtk::SeparatorToolItem sep2;
Gtk::Label label_title;
Gtk::Window wnd;
Gtk::Dialog dlg;
Gtk::ScrolledWindow scroll;
bool modal;
Gtk::Button *b_apply_ptr;
Gtk::Button *b_close_ptr;
//bool vkb_displayed;
bool result_ok;
//bool pseudo_dialog;
VirtualKeyboard keyboard;
Gtk::VSeparator keyboard_separator;
bool fullscreen;
bool exposed;
int lastx, lasty;
Gtk::Alignment kb_align;
};
struct AppliViewPrm
{
AppliViewPrm();
GColor background_color;
/** @brief Color for the labels */
bool overwrite_system_label_color;
GColor att_label_color;
/** If fixed size, screen is constrained to rect(ox,oy,dx,dy) */
bool fixed_size;
int dx, dy;
int ox, oy;
bool fullscreen;
bool use_touchscreen;
bool inverted_colors;
bool use_decorations;
bool use_button_toolbar;
std::string img_cancel;
std::string img_validate;
/* minimum space from bottom */
//uint32_t minimum_space_bottom;
/* minimum space between keyboard and window */
//uint32_t minimum_space_middle;
/** Virtual keyboard below the apply / validate buttons */
bool vkeyboard_below;
};
extern AppliViewPrm appli_view_prm;
}
}
#endif
| 19,694
|
C++
|
.h
| 667
| 25.431784
| 123
| 0.708296
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,033
|
ColorCellRenderer2.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/ColorCellRenderer2.hpp
|
#ifndef COLORCELLRENDERER2_H_
#define COLORCELLRENDERER2_H_
#include <gdkmm.h>
#include <gtkmm/cellrenderer.h>
#include <glibmm/property.h>
#include "mmi/ColorCellEditable2.hpp"
namespace utils
{
namespace mmi
{
class ColorCellRenderer2 : public Gtk::CellRenderer
{
public:
ColorCellRenderer2(std::vector<std::string> constraints);
virtual ~ColorCellRenderer2();
// Properties
Glib::PropertyProxy< Glib::ustring > property_text();
Glib::PropertyProxy< bool > property_editable();
// Edited signal
typedef sigc::signal<void, const Glib::ustring&, const Glib::ustring& > signal_edited_t;
signal_edited_t& signal_edited() { return signal_edited_; };
protected:
std::vector<std::string> constraints;
Glib::Property<Glib::ustring> property_text_;
Glib::Property<bool> property_editable_;
signal_edited_t signal_edited_;
ColorCellEditable2* color_cell_edit_ptr_;
mutable int button_width_; //mutable because it is just a cache for get_size_vfunc
// Raise the edited event
void edited(const Glib::ustring& path, const Glib::ustring& new_text);
virtual void get_size_vfunc (Gtk::Widget& widget, const Gdk::Rectangle* cell_area, int* x_offset, int* y_offset, int* width, int* height) const;
// TODO
//virtual void render_vfunc (const Glib::RefPtr<Gdk::Drawable>& window, Gtk::Widget& widget, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, const Gdk::Rectangle& expose_area, Gtk::CellRendererState flags);
virtual bool activate_vfunc (GdkEvent*, Gtk::Widget&, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags);
virtual Gtk::CellEditable* start_editing_vfunc(GdkEvent* event, Gtk::Widget& widget, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags);
// Manage editing_done event for color_cell_edit_ptr_
void on_editing_done();
};
}
}
#endif /*COLORCELLRENDERER2_H_*/
| 1,978
|
C++
|
.h
| 41
| 46.268293
| 231
| 0.768229
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,034
|
mmi-gen.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/mmi-gen.hpp
|
#ifndef MY_MMI_GEN_H
#define MY_MMI_GEN_H
#include "cutil.hpp"
#include "mmi/gtkutil.hpp"
#include "mmi/stdview.hpp"
#include "modele.hpp"
#include <gtkmm/scale.h>
#include <gtkmm/menubar.h>
#include "../journal.hpp"
namespace utils { namespace mmi {
struct MMIGenSection
{
MMIGenSection(utils::model::Node modele);
JFrame frame;
utils::model::Node modele;
utils::mmi::NodeView *vue;
Gtk::VBox vbox;
Gtk::HButtonBox bbox;
};
class MMIGen:
public Gtk::Window
{
public:
MMIGen();
MMIGen(utils::CmdeLine &cmdline, utils::model::Node modele, FileSchema *root);
int setup(utils::CmdeLine &cmdline, utils::model::Node modele, FileSchema *root);
static MMIGen *get_instance();
MMIGenSection *lookup(std::string nom);
protected:
struct ActionEvent{};
struct Action: public utils::CProvider<ActionEvent>
{
std::string id;
Gtk::ToolButton bouton;
};
std::vector<Action *> actions;
Action *recherche_action(const std::string &id);
virtual void gere_fin_application() {}
Gtk::Toolbar barre_outils;
unsigned int ncolonnes;
CmdeLine cmdline;
utils::model::Node modele_mmi; // Modèle statique, pour construire l'IHM
utils::model::Node modele; // Modèle de donnée dynamique
utils::model::NodeSchema *schema_vue; // Schéma construit
std::vector<MMIGenSection *> sections;
Gtk::VBox vbox_princ;
Gtk::Frame frame_menu;
std::vector<Gtk::VBox *> vboxes;
Gtk::HBox hbox;//, hb1, hb2;
Gtk::ProgressBar progress;
Glib::RefPtr<Gtk::TextBuffer> text_buffer;
Gtk::ScrolledWindow text_scroll;
Gtk::TextView text_view;
std::string historique;
// Barre d'outils
Gtk::ToolButton b_open, b_infos, b_exit, b_save;
Gtk::MenuBar barre_menu;
void gere_bouton(std::string id);
void on_b_save();
void on_b_open();
void on_b_infos();
void on_b_exit();
void on_b_non_gere(){}
virtual void maj_vue();
void maj_langue();
void set_histo(std::string text);
void put_histo(std::string text);
void put_histo_temp(std::string text);
int lock;
private:
void init();
};
}}
#endif
| 2,070
|
C++
|
.h
| 74
| 25.108108
| 83
| 0.720528
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,035
|
ColorCellEditable2.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/ColorCellEditable2.hpp
|
#ifndef COLORCELLEDITABLE2_H_
#define COLORCELLEDITABLE2_H_
#include <gtkmm/celleditable.h>
#include <gtkmm/eventbox.h>
#include <gtkmm/box.h>
#include <gdkmm/color.h>
#include <gtkmm/entry.h>
#include <gtkmm/button.h>
#include <gtkmm/drawingarea.h>
#include <cairomm/context.h>
namespace utils
{
namespace mmi
{
class ColorArea : public Gtk::DrawingArea
{
public:
ColorArea()
{};
virtual ~ColorArea()
{};
Gdk::Color get_color() const { return color_; };
void set_color(const Gdk::Color& value) { color_ = value; };
bool on_expose_event(GdkEventExpose* event)
{
// This is where we draw on the window
Glib::RefPtr<Gdk::Window> window = get_window();
if(window)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context();
// clip to the area indicated by the expose event so that we only redraw
// the portion of the window that needs to be redrawn
cr->rectangle(event->area.x, event->area.y,
event->area.width, event->area.height);
cr->clip();
cr->rectangle(0, 0, width, height);
cr->set_source_rgb (color_.get_red_p(), color_.get_green_p(), color_.get_blue_p());
cr->fill();
}
return true;
}
protected:
Gdk::Color color_;
};
class ColorCellEditable2 : public Gtk::EventBox, public Gtk::CellEditable
{
public:
// Ctor/Dtor
ColorCellEditable2(const Glib::ustring& path, std::vector<std::string> constraints);
virtual ~ColorCellEditable2();
// Return creation path
Glib::ustring get_path() const;
// Get and set text
void set_text(const Glib::ustring& text);
Glib::ustring get_text() const;
// Editing cancelled
bool get_editing_cancelled() const { return editing_cancelled_; };
// Return button width
static int get_button_width();
// Return ColorArea width
static int get_color_area_width();
// Signal for editing done
typedef sigc::signal<void> signal_editing_done_t;
signal_editing_done_t& signal_editing_done() { return signal_editing_done_; };
protected:
std::vector<std::string> constraints;
Glib::ustring path_;
ColorArea* color_area_ptr_;
Gtk::Entry* entry_ptr_;
Gtk::Button* button_ptr_;
Gdk::Color color_;
bool editing_cancelled_;
signal_editing_done_t signal_editing_done_;
/* override */virtual void start_editing_vfunc(GdkEvent* event);
/* override */virtual void on_editing_done();
/* override */virtual void on_entry_activate();
// Manage button_clicked signal
virtual void on_button_clicked();
// Manage entry_key_press_event signal
bool on_entry_key_press_event(GdkEventKey* event);
};
}
}
#endif /*COLORCELLEDITABLE2_H_*/
| 2,767
|
C++
|
.h
| 87
| 28.666667
| 89
| 0.714989
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,036
|
docking.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/docking.hpp
|
#ifndef DOCKING_H
#define DOCKING_H
#include "mmi/gtkutil.hpp"
#include "gtkmm/toggleaction.h"
namespace utils { namespace mmi {
class VueDetachable;
//class MGCWnd;
//class MainDock;
class Controle
{
public:
utils::model::Localized titre;
std::string id;
Gtk::Widget *widget;
utils::model::Node modele, modele_dyn;
virtual void maj_langue() {}
virtual ~Controle(){}
protected:
};
class MyPaned: public Gtk::Container
{
public:
struct Enfant
{
int num;
int valeur_affectee;
int valeur_forcee;
float valeur_forcee_pourcent;
Gtk::Allocation allocation[2];
int largeur, dim, dim_temp, dim_mini, dim_nat;
float hauteur_pourcent;
int valeur_min;
Gtk::Widget *widget;
Gtk::Separator *sep;
Gtk::HSeparator hsep;
Gtk::VSeparator vsep;
Gtk::EventBox event_box;
};
int get_dim(Gtk::Widget *wid);
int set_dim(Gtk::Widget *wid, int dim);
bool a_eu_allocation;
MyPaned(bool vertical = true);
~MyPaned();
void add_child(Gtk::Widget &w, int apres = -1);
Gtk::Widget *get_widget();
//void remove(Gtk::Widget &w);
std::deque<Enfant *> enfants;
protected:
void maj_allocation();
unsigned int total_height;
unsigned int total_minimum_dim, total_natural_dim;
void est_taille_min(int &largeur, int &hauteur);
virtual Gtk::SizeRequestMode get_request_mode_vfunc() const;
virtual void get_preferred_width_vfunc(int& minimum_width, int& natural_width) const;
virtual void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const;
virtual void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const;
virtual void get_preferred_width_for_height_vfunc(int height, int& minimum_width, int& natural_width) const;
virtual void on_size_allocate(Gtk::Allocation& allocation);
virtual void forall_vfunc(gboolean include_internals, GtkCallback callback, gpointer callback_data);
virtual void on_add(Gtk::Widget* child);
virtual void on_remove(Gtk::Widget* child);
virtual GType child_type_vfunc() const;
private:
unsigned int get_n_visible_children() const;
bool gere_motion(GdkEventMotion *mot);
bool gere_enter(GdkEventCrossing *mot, Enfant *e);
bool gere_leave(GdkEventCrossing *mot);
bool gere_bpress(GdkEventButton *mot, Enfant *e);
bool gere_brelease(GdkEventButton *mot, Enfant *e);
bool vertical, deplacement;
float last_dep, deplacement_pos_initiale;
int deplacement_taille_initiale[2];
Enfant *enfant_en_cours;
Gtk::Allocation derniere_allocation;
int tl_min, th_min;
friend class MainDock;
bool force_realloc;
};
class MyHPaned: public Gtk::HPaned
{
public:
MyHPaned();
MyHPaned(int largeur, int position);
void set_contrainte(int largeur, int position);
void applique_contrainte();
int numero;
bool forcer_position;
//void set_position(int position) override;
protected:
void on_size_allocate(Gtk::Allocation &allocation) /*override*/;
private:
int largeur, position;
};
struct DockItem
{
VueDetachable *vd;
};
struct Dock
{
std::vector<DockItem> items;
};
class MainDock
{
public:
MainDock(utils::model::Node modele);
Gtk::Widget *get_widget();
Gtk::VBox vbox;
void sauve();
void charge();
void maj_langue();
//MyHPaned hpaned[2];
MyPaned hpaned;
Dock docks[2];
VueDetachable *recherche(std::string id);
MyPaned vboxes[2];
std::vector<VueDetachable *> controles;
private:
void gere_drag_data_received(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time, int num);
void gere_drag_data_received_gauche(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time);
void gere_drag_data_received_droit(
const Glib::RefPtr<Gdk::DragContext>& context, int b, int c,
const Gtk::SelectionData& selection_data, unsigned int a, unsigned int time);
bool gere_drag_motion(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, unsigned int prm);
utils::model::Node modele;
friend class VueDetachable;
friend class MGCWnd;
};
class MyFrame: public Gtk::VBox
{
public:
MyFrame();
void set_titre(std::string s);
void add(Gtk::Widget &w);
void remove();
Gtk::Label titre;
Gtk::EventBox evbox;
Gtk::Button b_fermer, b_dedocquer;
Gtk::HBox hbox, hbox2;
Gtk::Alignment align;
Gtk::Widget *widget_en_cours;
};
class VueDetachable
{
public:
VueDetachable(Controle *controle, MainDock *main_dock);
void affiche(bool visible);
Controle *controle;
bool visible, docquee, docquable;
int doc_en_cours;
Glib::RefPtr<Gtk::ToggleAction> toggle;
void sauve_position();
void charge_position();
bool est_visible();
bool on_expose_event(const Cairo::RefPtr<Cairo::Context> &cr);
void maj_langue();
private:
bool gere_evt_delete(GdkEventAny *evt);
void gere_dedocquage();
void gere_fermeture();
MainDock *main_dock;
void maj_vue();
Gtk::Widget *item;
void gere_drag_data_get(
const Glib::RefPtr<Gdk::DragContext>& context,
Gtk::SelectionData& selection_data, unsigned int info, unsigned int time);
bool gere_drag_motion(
const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, unsigned int time);
Gtk::Window wnd;
bool expose;
MyFrame drag_frame;
friend class MainDock;
};
}}
#endif
| 5,484
|
C++
|
.h
| 179
| 27.273743
| 111
| 0.728952
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,037
|
gtkutil.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/gtkutil.hpp
|
/**
* This file is part of LIBCUTIL.
*
* LIBCUTIL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBCUTIL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBCUTIL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef GTKUTIL_HPP
#define GTKUTIL_HPP
//#include <gtkmm.h>
#include <cstddef>
using std::ptrdiff_t;
#include <gtkmm/grid.h>
#include <gtkmm/button.h>
#include <gtkmm/window.h>
#include <gtkmm/frame.h>
#include <gtkmm/alignment.h>
#include <gtkmm/buttonbox.h>
#include <gtkmm/cellrenderer.h>
#include <gtkmm/checkbutton.h>
#include <gtkmm/colorbutton.h>
#include <gtkmm/colorselection.h>
#include <gtkmm/combobox.h>
#include <gtkmm/dialog.h>
#include <gtkmm/drawingarea.h>
#include <gtkmm/entry.h>
#include <gtkmm/filechooser.h>
#include <gtkmm/filechooserbutton.h>
#include <gtkmm/filechooserdialog.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
#include <gtkmm/liststore.h>
#include <gtkmm/menu.h>
#include <gtkmm/menutoolbutton.h>
#include <gtkmm/notebook.h>
#include <gtkmm/paned.h>
#include <gtkmm/radiobutton.h>
#include <gtkmm/scrollbar.h>
#include <gtkmm/spinbutton.h>
#include <gtkmm/table.h>
#include <gtkmm/fixed.h>
#include <gtkmm/scrolledwindow.h>
#include <gtkmm/treestore.h>
#include <gtkmm/toolbar.h>
#include <gtkmm/separatortoolitem.h>
#include <gtkmm/uimanager.h>
#include <gtkmm/separator.h>
#include <gtkmm/main.h>
#include <gtkmm/aboutdialog.h>
#include <gtkmm/progressbar.h>
#include <gtkmm/toggleaction.h>
#include <gtkmm/stock.h>
#include <gtkmm/messagedialog.h>
#include <gtkmm/eventbox.h>
#include <gtkmm/textview.h>
#include <gtkmm/arrow.h>
#include <glibmm/dispatcher.h>
#include <gdkmm/cursor.h>
#include <cairomm/surface.h>
#include "cutil.hpp"
#include "../journal.hpp"
#include "modele.hpp"
namespace utils
{
namespace mmi
{
using namespace model;
//////////////////////////////////////////////////
// Global functions //
//////////////////////////////////////////////////
extern void show_frame_window(Gtk::Widget *frame, std::string name);
extern Glib::ustring request_user_string(Gtk::Window *parent,
Glib::ustring mainMessage,
Glib::ustring subMessage);
/** The theme must be localated in a folder with
* the same name as the theme one. */
extern void set_theme(std::string theme_name);
extern Gtk::Window *mainWindow;
namespace dialogs
{
extern std::string enregistrer_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name = "", std::string default_dir = "");
extern std::string ouvrir_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name = "", std::string default_dir = "");
extern std::string selection_dossier(const std::string &titre);
extern std::string nouveau_fichier(std::string title, std::string filter, std::string filter_name,
std::string default_name = "", std::string default_dir = "");
extern bool check_dialog(std::string title,
std::string short_description = "",
std::string description = "");
extern void affiche_infos(std::string titre, std::string description_courte = "", std::string description = "");
extern void affiche_erreur(std::string title, std::string short_description = "", std::string description = "");
extern void affiche_avertissement(std::string title, std::string short_description = "", std::string description = "", bool blocking = true);
extern void affiche_infos_localisee(const std::string &id_locale);
extern void affiche_avertissement_localise(const std::string &id_locale);
extern void affiche_erreur_localisee(const std::string &id_locale);
extern std::string enregistrer_fichier_loc(const std::string &id_locale,
const std::string filtre, const std::string &id_filtre,
const std::string &default_dir = "");
extern std::string ouvrir_fichier_loc(const std::string &id_locale,
const std::string &filtre, const std::string &id_filtre,
std::string default_dir = "");
}
//////////////////////////////////////////////////
// Objects //
//////////////////////////////////////////////////
class GColor
{
public:
uint8_t red, green, blue;
GColor(){red=0;green=0;blue=0;}
GColor(uint8_t r, uint8_t g, uint8_t b){red=r;green=g;blue=b;}
GColor(const Gdk::Color &col)
{
red = col.get_red() >> 8;
green = col.get_green() >> 8;
blue = col.get_blue() >> 8;
}
GColor gain(float a) const
{
GColor res;
float val = red * a;
if(val > 255)
val = 255;
res.red = (uint8_t) val;
val = green * a;
if(val > 255)
val = 255;
res.green = (uint8_t) val;
val = blue * a;
if(val > 255)
val = 255;
res.blue = (uint8_t) val;
return res;
}
Gdk::Color to_gdk() const
{
Gdk::Color res;
res.set_red(256 * red);
res.set_green(256 * green);
res.set_blue(256 * blue);
return res;
}
uint32_t to_int() const
{
uint32_t res = (blue << 16) | (green << 8) | red;
return res;
}
GColor(std::string desc)
{
std::vector<int> vec;
utils::str::parse_int_list(desc, vec);
if(vec.size() < 3)
return;
red = vec[0];
green = vec[1];
blue = vec[2];
}
std::string to_string() const
{
return utils::str::int2str(red) + "."
+ utils::str::int2str(green) + "."
+ utils::str::int2str(blue);
}
std::string to_html_string() const
{
return "#" + utils::str::int2strhexa(red, 8)
+ utils::str::int2strhexa(green, 8)
+ utils::str::int2strhexa(blue, 8);
}
};
// To deprecate
namespace AntiliasingDrawing
{
extern void draw_line(uint32_t *img,
uint32_t img_width,
uint32_t img_height,
int x1, int y1,
int x2, int y2,
GColor color,
bool mat_on_white);
}
class JFrame : public Gtk::Frame
{
public:
JFrame(){lab = nullptr;}
JFrame(std::string label);
void set_label(const Glib::ustring &s);
private:
Gtk::Label *lab;
};
class JComboBox: public Gtk::ComboBox
{
public:
JComboBox();
void add_key(std::string key);
std::string get_current_key();
void set_current_key(std::string s);
void remove_all();
private:
std::vector<std::string> keys;
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<Glib::ustring> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
};
class GtkLed;
class LedEvent
{
public:
GtkLed *source;
};
class GtkLed:
public CProvider<LedEvent>,
public Gtk::DrawingArea
{
public:
GtkLed(unsigned int size = 13, bool is_red = false, bool is_mutable = true);
void update_view();
void light(bool on);
bool is_on();
void set_red(bool is_red);
void set_yellow();
void set_sensitive(bool sensistive);
void set_mutable(bool is_mutable);
protected:
bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) /*override*/;
private:
bool is_sensitive;
unsigned int size;
bool is_mutable;
bool is_red, is_yellow;
bool realized;
bool is_lighted;
//Glib::RefPtr<Gdk::Window> wnd;
//Cairo::RefPtr<Cairo::Context> gc;
//bool on_expose_event(GdkEventExpose* event);
//void on_the_realisation();
//Glib::RefPtr<Pango::Layout> lay;
bool on_mouse(GdkEventButton *event );
};
class GtkKey;
class KeyChangeEvent
{
public:
GtkKey *source;
std::string key;
bool active;
};
class GtkKey:
public Gtk::DrawingArea,
public CProvider<KeyChangeEvent>
{
public:
GtkKey(unsigned short size_x = 40, unsigned short size_y = 40, std::string s = "", bool toggle = false);
void set_text(std::string s);
void set_text(char c);
std::string get_text();
void set_sensitive(bool sensitive);
private:
bool on_expose_event(GdkEventExpose* event);
void on_the_realisation();
bool on_mouse(GdkEventButton *event);
void update_view();
std::string text;
Cairo::RefPtr<Cairo::Context> ctx;
Glib::RefPtr<Gdk::Window> wnd;
Cairo::RefPtr<Cairo::Context> gc;
Glib::RefPtr<Pango::Layout> lay;
unsigned short size_x, size_y;
bool realized;
bool clicking;
bool toggle;
bool sensitive;
};
class VirtualKeyboard
: public JFrame,
private CListener<KeyChangeEvent>
{
public:
VirtualKeyboard(Gtk::Window *target_window);
~VirtualKeyboard();
/** @brief Setup currently valid characters (as UTF-8 strings) */
void set_valid_chars(const std::vector<std::string> &vchars);
std::deque<GtkKey *> keys;
Gtk::Fixed fixed;
Gtk::HBox hbox;
Gtk::Window *target_window;
private:
bool maj_on;
bool currently_active;
bool on_key(GdkEventKey *event);
void on_event(const KeyChangeEvent &kce);
unsigned long cx, cy;
unsigned long kw;
GtkKey *add_key(std::string s);
std::string class_name() const {return "graphic keyboard";}
void update_keyboard();
};
class Wizard;
class WizardStep
{
public:
std::string name;
std::string title;
std::string description;
Gtk::Frame *get_frame();
Wizard *parent;
virtual ~WizardStep(){}
virtual void validate() = 0;
virtual void enter() = 0;
virtual bool enable_next(){return false;}
virtual bool enable_end(){return false;}
virtual bool enable_prec(){return true;}
private:
};
/** @brief A wizard */
class Wizard
{
friend class WizardStep;
public:
Wizard() : wizlab("./img/wiznew.png"){}
virtual ~Wizard(){}
std::string title;
void set_icon(const std::string &ipath);
void start();
void update_view();
virtual void on_next_step(std::string current) = 0;
virtual void on_prec_step(std::string current) = 0;
void set_current(std::string name);
protected:
// Wizard customization
WizardStep *current, *first;
void add_step(WizardStep *step);
WizardStep *get_step(std::string name);
// non-zero if user cancelation
int state;
int current_index;
private:
void on_cancel();
void on_prec();
void on_next();
Gtk::Window dialog;
Gtk::VBox vbox, hvbox;
Gtk::Image wizlab;
Gtk::HBox hhvbox;
Gtk::HButtonBox low_buts;
Gtk::Frame high, mid;
Gtk::Label main_label, description_label;
Gtk::Button b_cancel, b_prec, b_next;
std::vector<WizardStep *> steps;
};
class PageChange
{
public:
Gtk::Widget *previous_widget, *new_widget;
};
class PageClose
{
public:
Gtk::Widget *closed_widget;
};
class NotebookManager:
public Gtk::Notebook,
public CProvider<PageChange>,
public CProvider<PageClose>
{
public:
NotebookManager();
static const int POS_FIRST;
static const int POS_LAST;
/** @returns page index if > 0 */
int add_page(int position, Gtk::Widget &widget, std::string name, std::string icon_path, std::string description = "");
int remove_page(Gtk::Widget &widget);
Gtk::Widget *get_current_page();
int set_current_page(Gtk::Widget &widget);
unsigned int nb_pages() const;
private:
class Page
{
public:
~Page();
Gtk::Widget *widget;
Gtk::Alignment *align;
int index;
std::string name;
std::string icon_path;
Gtk::ScrolledWindow scroll;
private:
};
int current_page;
std::deque<Page *> pages;
std::string class_name() const {return "notebook-manager";}
void on_switch_page(Gtk::Widget *page, int page_num);
void on_b_close(Page *page);
};
class SelectionChangeEvent
{
public:
Node old_selection, new_selection;
};
class VarEventFunctor
{
public:
virtual ~VarEventFunctor(){}
virtual int call(Node target) = 0;
std::string action;
};
template <class A>
class SpecificVarEventFunctor: public VarEventFunctor
{
public:
SpecificVarEventFunctor(A *object, int(A::*m_function)(Node target))
{
this->object = object;
this->m_function = m_function;
}
virtual int call(Node target)
{
return (*object.*m_function)(target);
}
private:
int (A::*m_function)(Node target);
A *object;
};
class TreeManager
: public JFrame,
public CProvider<SelectionChangeEvent>,
private CListener<ChangeEvent>
{
public:
TreeManager();
void set_liste_noeuds_affiches(const std::vector<std::string> &ids);
void set_model(Node model);
TreeManager(Node model);
Node get_selection();
int set_selection(Node elt);
void maj_langue();
template<class A>
int add_action_listener(std::string action, A *target, int (A:: *fun)(Node target));
private:
bool a_enfant_visible(const utils::model::Node noeud);
bool verifie_type_gere(const std::string &id);
std::vector<std::string> ids;
Glib::RefPtr<Gdk::Pixbuf> get_pics(const NodeSchema *schema);
bool has_pic(const NodeSchema *schema);
void load_pics(const NodeSchema *sc);
void populate();
void populate(Node m, const Gtk::TreeModel::Row *row);
void update_view();
void clear_table();
void on_selection_changed();
void on_event(const ChangeEvent &pce);
void set_selection(Gtk::TreeModel::Row &root, Node reg);
void setup_row_view(Node elt);
void on_treeview_row_activated(const Gtk::TreeModel::Path &path, Gtk::TreeViewColumn *);
void on_menu(Node elt, std::string action);
void on_menup(std::pair<Node, std::string> pr);
std::string class_name() const {return "tree-mng";}
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns(){add(m_col_name); add(m_col_ptr); add(m_col_pic); add(m_col_desc);}
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Node> m_col_ptr;
Gtk::TreeModelColumn<Glib::ustring> m_col_desc;
Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > m_col_pic;
};
class MyTreeView : public Gtk::TreeView
{
public:
MyTreeView(TreeManager *parent);
virtual bool on_button_press_event(GdkEventButton *ev);
private:
TreeManager *parent;
};
Node model;
bool lock;
Gtk::ScrolledWindow scroll;
MyTreeView tree_view;
Glib::RefPtr<Gtk::TreeStore> tree_model;
ModelColumns columns;
Gtk::Menu popup_menu;
std::deque<std::pair<Glib::RefPtr<Gdk::Pixbuf>, const NodeSchema *> > pics;
std::deque<const NodeSchema *> pics_done;
std::deque<VarEventFunctor *> menu_functors;
};
template<class A>
int TreeManager::add_action_listener(std::string action, A *target,
int (A:: *fun)(Node target))
{
/* TODO: check if not already registered */
SpecificVarEventFunctor<A> *f = new SpecificVarEventFunctor<A>(target, fun);
f->action = action;
menu_functors.push_back(f);
return 0;
}
/** @brief Class to manage the position on the screen
* of a window / dialog, decide whether this window should use
* scroll bars (screen too small), and the position of the
* virtual keyboard if necessary (touch screen mode). */
class DialogManager
{
public:
class Placable
{
public:
virtual Gtk::Window *get_window() = 0;
virtual void force_scroll(__attribute__((unused)) int dx, __attribute__((unused)) int dy){}
virtual void unforce_scroll(){}
};
static void get_screen(Gtk::Window *wnd, uint32_t &ox, uint32_t &oy, uint32_t &x, uint32_t &y);
/** @brief Place a window on the screen,
* optionnaly enabling its scrolling bars if the screen is too small. */
static void setup_window(Placable *wnd, bool fullscreen = false);
static void setup_window(Gtk::Window *wnd, bool fullscreen = false);
private:
};
class ColorRectangle: public Gtk::DrawingArea
{
public:
ColorRectangle(const GColor &col, uint16_t width, uint16_t height);
void update_color(const GColor &col);
~ColorRectangle();
private:
GColor col;
uint16_t width, height;
bool realized;
Glib::RefPtr<Gdk::Window> wnd;
Cairo::RefPtr<Cairo::Context> gc;
bool on_expose_event(const Cairo::RefPtr<Cairo::Context> &cr);
void on_the_realisation();
void update_view();
bool on_timer(int unused);
};
class ColorButton: public Gtk::Button,
private CListener<ChangeEvent>
{
public:
ColorButton(Attribute *model);
~ColorButton();
private:
void on_event(const ChangeEvent &ce);
void on_b_pressed();
Gtk::Alignment al;
Gtk::VBox box;
Attribute *model;
ColorRectangle *crec;
bool lock;
};
/** Dialog with custom toolbar in touchscreen mode */
class GenDialog: public Gtk::Dialog,
public DialogManager::Placable
{
public:
int display_modal();
virtual Gtk::Window *get_window();
protected:
typedef enum GenDialogTypeEnum
{
GEN_DIALOG_APPLY_CANCEL = 0,
GEN_DIALOG_VALID_CANCEL = 1,
GEN_DIALOG_CANCEL = 2,
GEN_DIALOG_CLOSE = 3
} GenDialogType;
GenDialog(GenDialogType type,
std::string title = "");
void enable_validation(bool enable);
virtual void on_cancel() {};
virtual void on_close() {};
virtual void on_valid() {};
virtual void on_apply() {};
Gtk::Box *vbox;
private:
void on_b_apply_valid();
void on_b_cancel_close();
GenDialogType type;
bool result_ok;
Gtk::Toolbar toolbar;
Gtk::ToolButton tool_valid, tool_cancel;
Gtk::SeparatorToolItem sep2;
Gtk::Button b_valid, b_cancel, b_apply;
Gtk::Label label_title;
Gtk::HButtonBox hbox;
};
class ColorDialog: public GenDialog
{
public:
ColorDialog();
int display(GColor initial_color, std::vector<std::string> constraints);
void force_scroll(int dx, int dy);
void unforce_scroll();
GColor get_color();
private:
void on_valid();
void on_cancel();
Gtk::ColorSelection cs;
GColor selected;
};
class ColorPalette: public Gtk::DrawingArea
{
public:
ColorPalette(const std::vector<GColor> &colors, uint32_t initial_color = 0);
~ColorPalette();
uint32_t current_color;
private:
int ncols, nrows;
std::vector<GColor> colors;
uint32_t width, height;
uint32_t c_width, c_height;
uint32_t spacing;
bool realized;
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
bool on_expose_event(GdkEventExpose *event);
void on_the_realisation();
void update_view();
bool on_mouse(GdkEventButton *event);
};
class ColorPaletteDialog: public GenDialog
{
public:
ColorPaletteDialog(const std::vector<GColor> &colors,
uint32_t initial_color);
~ColorPaletteDialog();
uint32_t color_index;
protected:
virtual void on_valid();
virtual void on_cancel();
private:
std::vector<GColor> colors;
ColorPalette palette;
};
/** A one end, listen to asynchronous generic 'A' type events
* At the other end, provides the same 'A' type events, synchronously
* inside the GTK thread. */
template<class A>
class GtkDispatcher: public CListener<A>, public CProvider<A>
{
public:
GtkDispatcher(uint32_t fifo_capacity = 4): fifo(fifo_capacity)
{
gtk_dispatcher.connect(sigc::mem_fun(*this, &GtkDispatcher::on_dispatcher));
}
void on_event(const A &a)
{
if(fifo.full())
{
//avertissement("GtkDispatcher : la fifo est pleine (%d elements).", fifo.size());
clear();
//utils::erreur("GtkDispatcher : la fifo est pleine (%d elements).", fifo.size());
}
fifo.push(a);
gtk_dispatcher();
}
void clear()
{
fifo.clear();
}
bool is_full()
{
return fifo.full();
}
private:
Glib::Dispatcher gtk_dispatcher;
hal::Fifo<A> fifo;
void on_dispatcher()
{
while(!fifo.empty())
{
A a = fifo.pop();
CProvider<A>::dispatch(a);
}
}
private:
};
class VideoView: public Gtk::DrawingArea
{
public:
VideoView(uint16_t dx = 150, uint16_t dy = 100, bool dim_from_parent = true);
void get_dim(uint16_t &sx, uint16_t &sy);
void update(void *img, uint16_t sx, uint16_t sy);
void change_dim(uint16_t sx, uint16_t sy);
private:
struct Trame
{
void *img;
uint16_t sx, sy;
};
GtkDispatcher<Trame> dispatcher;
///////////////////////////////////
// Data protected by a mutex.
void *new_img;
uint16_t new_sx, new_sy;
///////////////////////////////////
bool dim_from_parent;
bool realise;
uint16_t csx, csy;
Cairo::RefPtr<Cairo::ImageSurface> image_surface;
Cairo::RefPtr<Cairo::Context> cr;
Glib::Dispatcher signal_video_update;
utils::hal::Mutex mutex_video_update;
void on_event(const Trame &t);
void do_update_view();
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr);
void on_the_realisation();
void draw_all();
bool on_expose_event(GdkEventExpose* event);
};
struct GtkVoid2{};
class GtkVoidDispatcher: public CListener<GtkVoid2>, public CProvider<GtkVoid2>
{
public:
GtkVoidDispatcher(uint32_t fifo_capacity = 4): fifo(4)
{
gtk_dispatcher.connect(sigc::mem_fun(*this, &GtkVoidDispatcher::on_dispatcher));
}
void on_event(const GtkVoid2 &a)
{
fifo.push(a);
gtk_dispatcher();
}
void do_dispatch()
{
GtkVoid2 a;
fifo.push(a);
gtk_dispatcher();
}
private:
Glib::Dispatcher gtk_dispatcher;
hal::Fifo<GtkVoid2> fifo;
void on_dispatcher()
{
if(fifo.empty())
{
/* spurious dispatch ! */
}
else
{
GtkVoid2 a = fifo.pop();
CProvider<GtkVoid2>::dispatch(a);
}
}
private:
};
struct LabelClick
{
std::string path;
enum
{
SEL_CLICK,
VAL_CLICK
} type;
};
class SensitiveLabel: public Gtk::EventBox,
public CProvider<LabelClick>
{
public:
SensitiveLabel(std::string path);
Gtk::Label label;
private:
bool on_button_press_event(GdkEventButton *event);
std::string path;
};
class NullFunctor
{
public:
virtual ~NullFunctor(){}
virtual void call() = 0;
};
template <class A>
class SpecificNullFunctor: public NullFunctor
{
public:
SpecificNullFunctor(A *object, void(A::*m_function)())
{
this->object = object;
this->m_function = m_function;
}
virtual void call()
{
(*object.*m_function)();
}
private:
void (A::*m_function)();
A *object;
};
class ProgressDialog: public Gtk::Dialog
{
public:
ProgressDialog();
~ProgressDialog();
/* To be called from IHM thread */
template<class A>
void start_progress(std::string title, std::string text,
A *target_class,
void (A:: *target_function)());
void set_widget(Gtk::Widget *wid);
void maj_texte(const std::string &s);
private:
enum Event
{
START,
EXIT,
};
Gtk::Widget *wid;
utils::hal::Fifo<Event> event_fifo;
void setup(std::string title, std::string text);
void thread_entry();
bool on_timer(int index);
void on_b_cancel();
struct Bidon{};
void on_event(const Bidon &bidon);
utils::mmi::GtkDispatcher<Bidon> gtk_dispatcher;
NullFunctor *functor;
utils::hal::Signal callback_done, can_start, exit_done;
Gtk::ProgressBar progress;
Gtk::Label label;
Gtk::ToolButton bt;
Gtk::Toolbar toolbar;
bool canceled;
Gtk::Frame iframe;
Gtk::SeparatorToolItem sep;
bool in_progress;
};
template<class A>
void ProgressDialog::start_progress(std::string title, std::string text,
A *target_class,
void (A:: *target_function)())
{
callback_done.clear();
functor = new SpecificNullFunctor<A>(target_class, target_function);
setup(title, text);
}
extern int verifie_dernier_demarrage();
extern int termine_appli();
class FenetreVisibiliteToggle
{
public:
FenetreVisibiliteToggle();
void config(Gtk::Window *fenetre,
Glib::RefPtr<Gtk::ActionGroup> agroup,
const std::string &id);
void affiche(bool visible = true);
bool est_visible() const;
private:
bool gere_evt_delete(GdkEventAny *evt);
void on_toggle();
bool visible;
Glib::RefPtr<Gtk::ToggleAction> toggle;
Gtk::Window *fenetre;
bool lock;
};
}
}
#endif
| 24,490
|
C++
|
.h
| 872
| 24.372706
| 143
| 0.677381
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,038
|
renderers.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/renderers.hpp
|
#ifndef RENDERERS_HPP
#define RENDERERS_HPP
#include <glibmm/property.h>
#include "../journal.hpp"
#include "modele.hpp"
#include "cutil.hpp"
#include "mmi/gtkutil.hpp"
namespace utils
{
namespace mmi
{
class RefCellEditable:
public Gtk::EventBox,
public Gtk::CellEditable
{
public:
// Ctor/Dtor
RefCellEditable(const Glib::ustring& path);//, Node model, std::string ref_name);
virtual ~RefCellEditable();
void setup_model(Node model, std::string ref_name);
// Return creation path
Glib::ustring get_path() const;
// Get and set text
void set_text(const Glib::ustring& text);
Glib::ustring get_text() const;
// Editing cancelled
bool get_editing_cancelled() const { return editing_cancelled_; };
// Return button width
static int get_button_width();
// Return ColorArea width
static int get_color_area_width();
// Signal for editing done
typedef sigc::signal<void> signal_editing_done_t;
signal_editing_done_t& signal_editing_done() { return signal_editing_done_; };
protected:
//std::vector<std::string> constraints;
Glib::ustring path_;
Node model;
std::string ref_name;
//ColorArea* color_area_ptr_;
Gtk::Label* entry_ptr_;
Gtk::Button* button_ptr_;
//Gdk::Color color_;
bool editing_cancelled_;
signal_editing_done_t signal_editing_done_;
/* override */virtual void start_editing_vfunc(GdkEvent* event);
/* override */virtual void on_editing_done();
/* override */virtual void on_entry_activate();
// Manage button_clicked signal
virtual void on_button_clicked();
// Manage entry_key_press_event signal
bool on_entry_key_press_event(GdkEventKey* event);
};
class RefCellRenderer
: public Gtk::CellRenderer
{
public:
RefCellRenderer();//Node model, std::string ref_name);
virtual ~RefCellRenderer();
// Properties
Glib::PropertyProxy< Glib::ustring > property_text();
Glib::PropertyProxy< bool > property_editable();
// Edited signal
typedef sigc::signal<void, const Glib::ustring&, const Glib::ustring&> signal_edited_t;
signal_edited_t& signal_edited() { return signal_edited_; };
protected:
//Node model;
//std::string ref_name;
Glib::Property< Glib::ustring > property_text_;
Glib::Property< bool > property_editable_;
signal_edited_t signal_edited_;
RefCellEditable *color_cell_edit_ptr_;
mutable int button_width_; //mutable because it is just a cache for get_size_vfunc
// Raise the edited event
void edited(const Glib::ustring& path, const Glib::ustring& new_text);
virtual void get_size_vfunc (Gtk::Widget& widget, const Gdk::Rectangle* cell_area, int* x_offset, int* y_offset, int* width, int* height) const;
// TODO
//virtual void render_vfunc (const Glib::RefPtr<Gdk::Drawable>& window, Gtk::Widget& widget, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, const Gdk::Rectangle& expose_area, Gtk::CellRendererState flags);
virtual bool activate_vfunc (GdkEvent*, Gtk::Widget&, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags);
virtual Gtk::CellEditable* start_editing_vfunc(GdkEvent* event, Gtk::Widget& widget, const Glib::ustring& path, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, Gtk::CellRendererState flags);
// Manage editing_done event for color_cell_edit_ptr_
void on_editing_done();
};
class RefExplorerChange
{
};
class RefExplorer: public Gtk::Frame,
public CProvider<RefExplorerChange>
{
public:
RefExplorer();
RefExplorer(Node model, std::string ref_name, const std::string &title = "");
void setup(Node model, std::string ref_name, const std::string &title = "");
Node get_selection();
private:
bool is_valid();
void populate();
void populate(Node m, Gtk::TreeModel::Row row);
void update_view();
void clear_table();
void on_treeview_row_activated(const Gtk::TreeModel::Path &path, Gtk::TreeViewColumn *);
void on_selection_changed();
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns(){add(m_col_name); add(m_col_ptr);} //add(m_col_pic); add(m_col_desc);}
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Node> m_col_ptr;
};
bool lock;
Gtk::ScrolledWindow scroll;
Gtk::TreeView tree_view;
Glib::RefPtr<Gtk::TreeStore> tree_model;
ModelColumns columns;
Node model;
std::string ref_name;
bool valid;
bool init_done;
};
/** A window to let the user select an object in a tree model */
class RefExplorerWnd: public GenDialog
{
public:
/** Create the window (do not show it).
* @param model: the tree to be explored.
* @param type: The type of node that the user can select. */
RefExplorerWnd(Node model, const std::string &type, const std::string &wnd_title = "");
/** Display the window (blocking call)
* @returns 0 if the user has not canceled. */
int display();
Node get_selection();
void update_view();
void on_change(const RefExplorerChange &change);
private:
RefExplorer explorer;
Node model;
std::string ref_name;
};
}
}
#endif
| 5,145
|
C++
|
.h
| 141
| 33.382979
| 232
| 0.725839
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,039
|
serial-ui.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/serial-ui.hpp
|
/**
* This file is part of LIBSERIAL.
*
* LIBSERIAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LIBSERIAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LIBSERIAL. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2007-2011 J. A.
*/
#ifndef SERIAL_UI_H
#define SERIAL_UI_H
#include "mmi/gtkutil.hpp"
#include "cutil.hpp"
#include "serial.hpp"
namespace utils
{
namespace comm
{
class SerialFrame: public JFrame
{
public:
SerialFrame(std::vector<SerialInfo> &infos, const SerialConfig &sc);
SerialConfig config;
void update_view();
private:
Gtk::Label l_com, l_deb;
Gtk::Table table;
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_name); add(m_col_lgname); }
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<Glib::ustring> m_col_lgname;
};
ModelColumns m_Columns;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
Gtk::ComboBox combo;
void on_combo_change();
class ModelColumns2 : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns2()
{ add(m_col_val); }
Gtk::TreeModelColumn<int> m_col_val;
};
ModelColumns2 m_Columns2;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel2;
Gtk::ComboBox combo2;
void on_combo2_change();
};
}
}
#endif
| 1,788
|
C++
|
.h
| 63
| 25.904762
| 79
| 0.734148
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,040
|
theme.hpp
|
tsdconseil_opencv-demonstrator/libcutil/include/mmi/theme.hpp
|
#ifndef THEME_H
#define THEME_H
//#ifdef MSYS2
#include <gtkmm/cssprovider.h>
//#include <csssection.h>
//#include <gtkmm/styleproperty.h>
//#endif
namespace utils{ namespace mmi{
struct Theme
{
std::string id;
std::string desc;
std::string chemin;
//# ifdef MSYS2
Glib::RefPtr<Gtk::CssProvider> provider;
//# endif
};
extern std::vector<Theme> themes;
extern int charge_themes();
extern int installe_theme(std::string th, bool tactile = false);
}}
#endif
| 482
|
C++
|
.h
| 22
| 19.727273
| 64
| 0.742152
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,041
|
model-editor.hpp
|
tsdconseil_opencv-demonstrator/libcutil/src/utilities/model-editor.hpp
|
#ifndef MODEL_EDITOR_HPP
#define MODEL_EDITOR_HPP
#include "mmi/stdview.hpp"
using namespace utils;
using namespace utils::model;
using namespace utils::mmi;
using namespace std;
class ModelEditor: public Gtk::Window,
private CListener<ChangeEvent>,
private CListener<EVSelectionChangeEvent>
{
public:
static ModelEditor *get_instance();
virtual ~ModelEditor();
int open(std::string filename);
int main(CmdeLine &cmdline);
ModelEditor();
private:
std::string ext, extname;
void on_event(const EVSelectionChangeEvent &evse);
/** Main horizontal separation */
Gtk::HPaned hpane;
/** View for the database */
NodeView *ev_root;
Gtk::VBox vbox, vboxi;
Gtk::Toolbar tools;
Gtk::ToolButton b_new, b_open, b_save, b_exit, b_param, b_about, b_infos;
/** View for the currently edited item */
NodeView *ev;
Gtk::ScrolledWindow scroll;
Node model;
static ModelEditor *instance;
bool model_saved;
/** Application configuration (path, etc.) */
Node config;
/** root-schema.xml */
FileSchema *root_fs;
NodeSchema *root_schema;
std::string model_path, schema_path;
std::string last_schema_dir;
void on_b_open();
void on_b_save();
void on_b_save_as();
void save_as(const string &filename);
void on_b_new();
void on_b_exit();
void on_b_comp();
void on_b_param();
void on_b_infos();
void update_view();
void on_event(const ChangeEvent &ce);
};
#endif
| 1,473
|
C++
|
.h
| 53
| 24.169811
| 75
| 0.705376
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,042
|
vue-image.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/vue-image.hpp
|
#ifndef VUE_IMAGE_H
#define VUE_IMAGE_H
#include "mmi/gtkutil.hpp"
#include <opencv2/imgproc.hpp>
namespace ocvext
{
class VueImage: public Gtk::DrawingArea
{
public:
VueImage(uint16_t dx = 150, uint16_t dy = 100, bool dim_from_parent = true);
void get_dim(uint16_t &sx, uint16_t &sy);
void maj(const cv::Mat &img);
void maj(const std::string &chemin_fichier);
void change_dim(uint16_t sx, uint16_t sy);
void coor_vue_vers_image(int xv, int yv, cv::Point &xi);
bool on_draw(const Cairo::RefPtr<Cairo::Context> &cr);
cv::Scalar arriere_plan;
protected:
//void on_size_allocate(Gtk::Allocation &allocation);
//void get_preferred_width(int& minimum_width, int& natural_width) const;
//void get_preferred_height(int& minimum_height, int& natural_height) const;
private:
float ratio;
cv::Point p0;
bool cr_alloue;
void change_dim_interne(uint16_t sx, uint16_t sy);
int alloc_x, alloc_y;
struct Trame
{
cv::Mat img;
};
utils::mmi::GtkDispatcher<Trame> dispatcher;
Trame en_attente;
///////////////////////////////////
// Data protected by a mutex.
cv::Mat new_img;
///////////////////////////////////
bool dim_from_parent;
bool realise;
uint16_t csx, csy;
Cairo::RefPtr<Cairo::ImageSurface> image_surface, old;
Cairo::RefPtr<Cairo::Context> cr;
Glib::Dispatcher signal_video_update;
utils::hal::Mutex mutex_video_update;
static std::vector<Cairo::RefPtr<Cairo::Context>> *old_srf;
void maj_surface(const cv::Mat &I);
void on_event(const Trame &t);
void do_update_view();
void on_the_realisation();
void draw_all();
//bool on_expose_event(GdkEventExpose* event);
bool gere_expose_event(GdkEventExpose* event);
};
class DialogueImage
{
public:
DialogueImage();
void affiche(cv::Mat &I, const std::string &titre, const std::string &infos);
Gtk::Dialog dialogue;
private:
void gere_b_fermer();
ocvext::VueImage vview;
Gtk::HButtonBox hbox;
Gtk::Button b_close;
};
}
#endif
| 1,988
|
C++
|
.h
| 67
| 26.80597
| 79
| 0.695354
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,043
|
thinning.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/thinning.hpp
|
#ifndef THINNING_H
#define THINNING_H
#include <opencv2/core.hpp>
namespace ocvext {
extern void thinning_Zhang_Suen(const cv::Mat& I, cv::Mat &O);
extern void thinning_Guo_Hall(const cv::Mat& I, cv::Mat &O);
extern void thinning_morpho(const cv::Mat &I, cv::Mat &O);
}
#endif
| 284
|
C++
|
.h
| 9
| 29.777778
| 62
| 0.738806
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,044
|
fourier.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/fourier.hpp
|
#ifndef FOURIER_H
#define FOURIER_H
#include "opencv2/core.hpp"
namespace ocvext
{
/** Recentrage d'une DFT 2D de manière à ce que
* le DC soit au centre de l'image */
extern void dft_shift(cv::Mat &mag);
/** Recentrage d'une DFT 2D de manière à ce que
* le DC soit au centre de l'image */
extern void ift_shift(cv::Mat &mag);
/** Détection du vecteur translation la plus probable entre deux images */
extern cv::Point detection_translation(const cv::Mat &I0, const cv::Mat &I1, bool normaliser_spectre = false, cv::Mat *spectre = nullptr);
extern int detection_rotation_echelle(const cv::Mat &I0, const cv::Mat &I1, float &angle, float &echelle);
extern void translation(const cv::Mat &I, cv::Mat &O, int offsetx, int offsety, const cv::Scalar &bg = cv::Scalar(0));
extern void translation_rapide(const cv::Mat &I, cv::Mat &O,
int decx, int decy,
const cv::Size &dim_sortie,
const cv::Scalar &bg = cv::Scalar(0));
extern int estime_periode(cv::Mat &I,
float &d, float &indice_confiance,
float dmin, float dmax,
cv::Mat *dbg = nullptr);
}
#endif
| 1,241
|
C++
|
.h
| 25
| 40.92
| 138
| 0.624582
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,045
|
gl.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/gl.hpp
|
/** @file ocvext/include/gl.hpp
* @brief Garcia-Lorca exponential filter and optimized Deriche gradient
* @author J.A. 2015 / www.tsdconseil.fr
* @license LGPL V 3.0 */
#ifndef GL_HPP
#define GL_HPP
#include "opencv2/core.hpp"
namespace ocvext
{
/** @brief Garcia-Lorca filtering
* @param I input image
* @param O output image (filtered)
* @param gamma Filtering coefficient between 0 and 1.
* 0 means no filtering, 1 means maximum filtering. */
extern int Deriche_blur(const cv::Mat &I,
cv::Mat &O,
float gamma);
/** @brief Gradient de Deriche
* @param I input image
* @param gx, gy Output gradient (along x and y axis)
* @param gamma Filtering coefficient between 0 and 1.
* 0 means no filtering, 1 means maximum filtering. */
extern int Deriche_gradient(const cv::Mat &I,
cv::Mat &gx,
cv::Mat &gy,
float gamma);
/** @brief Gradient de Deriche (norme du gradient)
* @param I input image
* @param O Output gradient norm (normalized between 0 and 255)
* @param gamma Filtering coefficient between 0 and 1.
* 0 means no filtering, 1 means maximum filtering. */
extern int Deriche_gradient(const cv::Mat &I,
cv::Mat &O,
float gamma);
}
#endif
| 1,364
|
C++
|
.h
| 36
| 31.194444
| 74
| 0.627748
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,046
|
calib.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/calib.hpp
|
#ifndef CALIB_H
#define CALIB_H
#include "ocvext.hpp"
#include "vue-image.hpp"
#include "images-selection.hpp"
namespace ocvext {
struct EtalonnageCameraConfig
{
enum Type
{
DAMIER = 0,
CIRC = 1
};
Type type;
int nlignes, ncolonnes;
float largeur_case_cm; // largeur d'une case, en cm
};
extern int etalonner_camera(const std::vector<cv::Mat> &imgs,
const EtalonnageCameraConfig &config,
cv::Mat &matrice_camera, cv::Mat &prm_dist);
class DialogueCalibration
{
public:
DialogueCalibration();
void affiche();
Gtk::Window dialogue;
private:
void thread_video();
void gere_b_cal();
void gere_b_fermer();
void gere_b_photo();
ocvext::VueImage vue_video;
ocvext::ImagesSelection img_list;
Gtk::HButtonBox hbox;
Gtk::VBox vbox;
Gtk::Button b_fermer, b_photo, b_cal;
Gtk::HPaned paned;
utils::model::Node prm;
utils::mmi::NodeView vue_prm;
utils::model::FileSchema fs;
bool prende_photo;
std::vector<cv::Mat> photos;
struct EvtGtk
{
};
utils::mmi::GtkDispatcher<EvtGtk> dispatcheur;
void gere_evt_gtk(const EvtGtk &eg);
};
}
#endif
| 1,122
|
C++
|
.h
| 50
| 19.54
| 61
| 0.719315
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,047
|
hough.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/hough.hpp
|
/** @file hough.hpp
* @brief Hough transform / using gradient
* @author J.A. / 2015 / www.tsdconseil.fr
* @license LGPL V 3.0 */
#ifndef HOUGH_E_HPP
#define HOUGH_E_HPP
#include "opencv2/core.hpp"
#include <vector>
#include <cmath>
namespace ocvext
{
//////////////////////////////////////////////////////
// Generic function to compute the Hough transform //
// (independant of the type of objects searched) //
//////////////////////////////////////////////////////
/** @brief Gradient direction-based Hough transform
* @param img Input image (can be BGR, graylevels, etc.)
* @param res Resulting accumulation space, with coordinates (rho,theta)
* @param theta Angular resolution (in radians)
* @param rho Distance resolution (in pixels)
* @param gamma Filtering factor between 0 (no filtering) and 1 (maximum filtering) for the Deriche gradient.
* @note Rho dimension is automatically computed from input image dimension and
* set such that the resolution is one pixel. */
extern void Hough_with_gradient_dir(const cv::Mat &img,
cv::Mat &res,
float rho = 1.0, // 1 pixel
float theta = 2 * 3.1415926 / 360, // 1 degree
float gamma = 0.6,
bool use_deriche = false);
/** @brief Gradient magnitude only based Hough transform
* @param img Input image (can be BGR, graylevels, etc.)
* @param res Resulting accumulation space, with coordinates (rho,theta)
* @param theta Angular resolution (in radians)
* @param rho Distance resolution (in pixels)
* @param gamma Filtering factor between 0 (no filtering) and 1 (maximum filtering) for the Deriche gradient.
* @note Rho dimension is automatically computed from input image dimension and
* set such that the resolution is one pixel. */
extern void Hough_without_gradient_dir(const cv::Mat &img,
cv::Mat &res,
float rho = 1.0, // 1 pixel
float theta = 2 * 3.1415926 / 360, // 1 degree
float gamma = 0.6);
//////////////////////////////////////////////////////
// Hough transform to detect specific objects //
//////////////////////////////////////////////////////
/** @brief Lines detection
* This function has the same first 4 parameters as
* the OpenCV native function "HoughLines".
* But it does not needs any threshold to be set. */
extern void Hough_lines_with_gradient_dir(const cv::Mat &img,
std::vector<cv::Vec2f> &lines,
cv::Mat &debug,
float rho = 1.0,
float theta = 2 * 3.1415926 / 360,
float gamma = 0.6,
float seuil = 0.4);
}
#endif
| 3,038
|
C++
|
.h
| 58
| 41.568966
| 112
| 0.533356
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,048
|
images-selection.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/images-selection.hpp
|
/** @file image-selecteur.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of libocvext.
libocvext is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libocvext is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef IMAGE_SELECTEUR_HPP
#define IMAGE_SELECTEUR_HPP
#include "mmi/gtkutil.hpp"
#include <gdkmm/pixbuf.h>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "cutil.hpp"
#include "mmi/stdview.hpp"
#include "vue-image.hpp"
namespace ocvext {
struct ImagesSelectionRefresh{};
/** @brief Sélecteur d'image */
class ImagesSelection:
public utils::CProvider<ImagesSelectionRefresh>
{
public:
ImagesSelection();
void maj_langue();
void maj_actif();
void ajoute_photo(const cv::Mat &I);
void ajoute_fichier(std::string s);
void raz();
void get_list(std::vector<cv::Mat> &list);
unsigned int get_nb_images() const;
bool has_video();
void get_video_list(std::vector<std::string> &list);
struct SpecEntree
{
enum
{
TYPE_IMG = 0,
TYPE_VIDEO,
TYPE_WEBCAM,
TYPE_IMG_RAM
} type;
bool is_video(){return (type == TYPE_WEBCAM) || (type == TYPE_VIDEO);}
std::string chemin;
unsigned int id_webcam;
cv::Mat img;
};
void get_entrees(std::vector<SpecEntree> &liste);
int nmin, nmax;
Gtk::Window fenetre;
private:
utils::model::FileSchema fs;
void set_fichier(int idx, std::string s);
std::string media_open_dialog(utils::model::Node mod);
void on_size_change(Gtk::Allocation &alloc);
bool on_b_pressed(GdkEventButton *event);
bool on_b_released(GdkEventButton *event);
bool on_k_released(GdkEventKey *event);
void on_b_open();
void on_b_add();
void on_b_del();
void on_b_del_tout();
void on_b_maj();
void on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time);
void maj_mosaique();
void maj_selection();
void maj_has_video();
///Gtk::Image gtk_image;
Gtk::EventBox evt_box;
ocvext::VueImage vue;
//Glib::RefPtr<Gdk::Pixbuf> pixbuf;
Gtk::VBox vbox;
Gtk::ToolButton b_suppr, b_open, b_suppr_tout, b_maj, b_ajout;
Gtk::Toolbar toolbar;
bool toolbar_est_pleine; // En ce moment, a les boutons b_suppr, b_suppr_tout et b_add ?
cv::Mat bigmat;
struct Image
{
SpecEntree spec;
std::string /*fichier,*/ nom;
//cv::Mat mat;
unsigned int ix, iy, px, py;
utils::model::Node modele; // Modèle de source
};
unsigned int ncols, nrows, col_width, row_height;
unsigned int img_width, img_height;
std::deque<Image> images;
int csel;
bool has_a_video;
};
}
#endif
| 3,321
|
C++
|
.h
| 100
| 29.57
| 150
| 0.711055
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,049
|
vue-collection.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/vue-collection.hpp
|
#ifndef VUE_COLLECTION_H
#define VUE_COLLECTION_H
#include <opencv2/imgproc.hpp>
#include "vue-image.hpp"
#include "mmi/stdview.hpp"
#include "vue-image.hpp"
namespace ocvext{
/*struct CollectionItem
{
std::string nom;
std::string chemin;
};
struct Collection
{
std::vector<CollectionItem> items;
};*/
class VueCollection
{
public:
VueCollection();
//void affiche(const Collection &col);
void affiche(utils::model::Node &modele);
void ferme();
Gtk::Window fenetre;
private:
void gere_b_ouvrir_image();
void gere_change_sel(const utils::mmi::SelectionChangeEvent &sce);
Gtk::Widget *vue_en_cours;
Gtk::VBox vbox, vbox_princ;
Gtk::TextView texte;
Gtk::HPaned hpaned;
utils::model::Node modele, modele_arbre;
VueImage vue;
utils::mmi::TreeManager arbre;
Gtk::Toolbar barre_outil;
Gtk::ToolButton b_ouvrir_image;
};
}
#endif
| 874
|
C++
|
.h
| 39
| 20.051282
| 68
| 0.74878
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,050
|
reco.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/reco.hpp
|
#ifndef RECO_H
#define RECO_H
#include <opencv2/features2d.hpp>
namespace ocvext {
struct AssociateurConfig
{
AssociateurConfig();
bool verifie_ratio;
bool verifie_symetrie;
float seuil_ratio;
};
class Associateur
{
public:
Associateur(const AssociateurConfig &config = AssociateurConfig());
void calcule(const cv::Mat &desc0, const cv::Mat &desc1,
std::vector<cv::DMatch> &res);
private:
AssociateurConfig config;
};
}
#endif
| 473
|
C++
|
.h
| 22
| 18.409091
| 69
| 0.75576
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,051
|
ocvext.hpp
|
tsdconseil_opencv-demonstrator/libocvext/include/ocvext.hpp
|
#ifndef MISC_H
#define MISC_H
#include "opencv2/core.hpp"
#include <string>
#include "modele.hpp"
namespace ocvext
{
class GestionnaireEvenementGenerique
{
public:
virtual ~GestionnaireEvenementGenerique(){}
virtual void maj_infos(const std::string &infos) = 0;
virtual void maj_infos(const std::string &infos, const cv::Mat &img) = 0;
};
extern GestionnaireEvenementGenerique *gestionnaire_evenement;
extern void infos_demarre_log(utils::model::Node &res, const std::string &id);
extern void infos_arrete_log();
//extern utils::model::Node infos_get_log();
extern void infos_entre_algo(const std::string &nom_algo);
extern void infos_sors_algo();
extern void infos_progression(const std::string &infos, ...);
extern void infos_progression(const std::string &infos, const cv::Mat &img, bool normaliser = false);
struct Config
{
std::string dout;
unsigned int img_cnt;
bool affiche_images_intermediaires;
bool enreg_images_intermediaires;
# ifdef WINDOWS
LARGE_INTEGER base_tick, frequency;
# endif
Config();
};
extern Config config;
extern void init(bool affiche_img_interm,
bool stocke_img_interm,
const std::string &dossier_stockage = "");
extern void defini_dossier_stockage(const std::string &chemin);
extern void defini_options_debogage(bool affiche_img_interm,
bool stocke_img_interm);
extern bool est_debogage_actif();
extern void dbg_image(const std::string &name,
const cv::Mat &m,
bool normalize = false,
const std::string &titre = "",
const std::string &description = "");
extern cv::Mat imread(const std::string &fn);
extern void redim_preserve_aspect(const cv::Mat &I,
cv::Mat &O,
const cv::Size &dim,
const cv::Scalar &bgcolor = cv::Scalar(0));
extern void plot_1d(cv::Mat &image, const cv::Mat &x_, cv::Scalar color);
struct MultiPlot
{
MultiPlot();
// sx,sy = taille par case
MultiPlot(uint16_t nx, uint16_t ny, uint16_t sx, uint16_t sy);
void init(uint16_t nx, uint16_t ny, uint16_t sx, uint16_t sy);
void ajoute(std::string nom, const cv::Mat &I, uint16_t ncols = 1);
void creation_auto(const cv::Mat &I0, const cv::Mat &I1);
uint16_t nx, ny, sx, sy;
uint16_t cnt;
cv::Mat img;
};
extern void adapte_en_bgr(const cv::Mat &I, cv::Mat &O);
extern void affiche_dans_cadre(const cv::Mat &I, cv::Mat &cadre,
cv::Size taille_vue, const cv::Scalar &arriere_plan);
extern void affiche_dans_cadre(const cv::Mat &I, cv::Mat &cadre,
cv::Size taille_vue, const cv::Scalar &arriere_plan,
cv::Point &p0, float &ratio);
}
#endif
| 2,787
|
C++
|
.h
| 72
| 32.777778
| 101
| 0.661836
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,052
|
ocvdemo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/ocvdemo.hpp
|
/** @file ocvdemo.hpp
@brief Classe principale pour le démonstrateur OpenCV
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef OCV_DEMO_H
#define OCV_DEMO_H
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include "cutil.hpp"
#include "mmi/stdview.hpp"
#include <assert.h>
#include <vector>
#include "mmi/gtkutil.hpp"
#include "hal.hpp"
#include "ocvdemo-item.hpp"
#include "tools/image-selecteur.hpp"
#include "tools/image-mosaique.hpp"
#include "tools/boutils-image.hpp"
using namespace utils;
using namespace utils::model;
using namespace utils::mmi;
using namespace cv;
/** Current software revision */
#ifndef VMAJ
# define VMAJ 1
# define VMIN 3
# define VPATCH 0
#endif
#ifndef OCV_VPATCH
# define OCV_VMAJ 3
# define OCV_VMIN 2
# define OCV_VPATCH 0
#endif
// TODO: remove this ugly hack
/*namespace utils
{
extern Localized::Language current_language;
}*/
/*struct OCVDemoParam
{
bool forcer_taille_fenetre_sortie;
uint16_t fenetre_sortie_sx, fenetre_sortie_sy;
};*/
struct OCVDemoFinAppli{};
////////////////////////////////////////////////////////////////////////////
/** @brief Classe principale pour le démonstrateur OpenCV */
class OCVDemo:
// Changement de sélection dans l'arbre
private CListener<utils::mmi::SelectionChangeEvent>,
// Changement d'un paramètre de calcul
private CListener<ChangeEvent>,
// Changement dans le sélecteur d'image
private CListener<ImageSelecteurRefresh>,
// Evenement souris
private CListener<OCVMouseEvent>,
// Demande de rafraichissement de la part d'une démo
private CListener<OCVDemoItemRefresh>,
public CProvider<OCVDemoFinAppli>
{
public:
/** Constructeur (devrait être privé !) */
OCVDemo(utils::CmdeLine &cmdeline,
const std::string &prefixe_modele = "");
//void ajoute_bouton(Gtk::ToolButton *bouton);
OCVDemoItem *recherche_demo(const std::string &nom);
/** Démarrage interface graphique */
void demarre_interface();
/** Singleton */
static OCVDemo *get_instance();
/** Export vers doc HTML pour site web */
std::string export_html(Localized::Language lg);
/** Export des images pour la doc HTML */
void export_captures();
FileSchema *get_fileschema(){return this->fs_racine;}
void add_demo(OCVDemoItem *demo);
utils::model::Node get_modele_global() {return this->modele_global;}
Gtk::Frame frame_menu;
private:
void thread_calcul();
void thread_video();
/** Demande le recalcul avec la dernière image d'entrée prête (dans I0) */
void update();
/** Réceptacle GTK pour une trame à partir du flux vidéo */
void on_video_image(const std::vector<cv::Mat> &tmp);
void release_all_videos();
bool are_all_video_ok();
void export_captures(utils::model::Node &cat);
Mat get_current_output();
bool has_output();
void setup_demo(const utils::model::Node &sel);
void maj_bts();
void maj_langue();
void maj_langue_systeme();
std::string export_demos(utils::model::Node &cat, Localized::Language lg);
void maj_entree();
void add_demos();
void on_menu_entree();
void on_menu_quitter();
void setup_menu();
// Evenement souris sur la fenêtre d'affichage
void on_event(const OCVMouseEvent &me);
// Changement modèle (démo en cours ou schéma global)
void on_event(const ChangeEvent &ce);
// Sélection d'une autre démo
void on_event(const utils::mmi::SelectionChangeEvent &e);
// Nouvelle image sélectionnée
void on_event(const ImageSelecteurRefresh &e);
// Demande de rafraichissement en provenance d'une démo
void on_event(const OCVDemoItemRefresh &e);
// Drag & drop
void on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, const Gtk::SelectionData& selection_data,
guint info, guint time);
bool on_delete_event(GdkEventAny *event);
void on_b_save();
void on_b_open();
void on_b_exit();
void on_b_infos();
void update_Ia();
void compute_Ia();
void masque_clic(int x, int y);
void masque_raz();
void on_b_masque_raz();
void on_b_masque_gomme();
void on_b_masque_remplissage();
// To communicate from the video thread to the main GTK thread
utils::mmi::GtkDispatcher<std::vector<cv::Mat>> gtk_dispatcher;
// Lock for video stream access.
utils::hal::Mutex mutex_video;
// Lock for update current output.
utils::hal::Mutex mutex_update;
std::string lockfile; // Chemin du fichier de lock
// Obsolete ?
utils::hal::Mutex mutex; // Verrou pour les calculs VS video
// Dialogue de démarrage
utils::mmi::NodeDialog *entree_dial;
// Pour le menu
Glib::RefPtr<Gtk::ActionGroup> agroup;
// Fenêtre principale
Gtk::Window wnd;
// Conteneur principal
Gtk::VBox vbox;
// Séparateur paneaux de gauche et droite
Gtk::HPaned hpaned;
// Modèles
utils::model::Node modele, modele_global, tdm;
utils::model::Node modele_demo; // Modèle dans la TOC
// Configuration de la démo en cours
utils::mmi::NodeView *rp;
// Arbre de sélection à gauche
TreeManager vue_arbre;
// Cadre autour de la config
JFrame cadre_proprietes;
// Schéma racine
FileSchema *fs_racine;
// Verrou
bool lock;
// Titre principal
std::string titre_principal;
// Affichage des résultats
ImageMosaique mosaique;
// Liste des démos supportées
std::vector<OCVDemoItem *> items;
// Démo en cours
OCVDemoItem *demo_en_cours;
// I0 : image originale
// I1 : telle que modifiée par le processus
// Ia : avec rectangle utilisateur
cv::Mat I0, I1, I, Ia;
int etat_souris;
// Région d'intérêt
cv::Rect rect_rdi;
cv::Point rdi0, rdi1;
// Vidéo en cours ?
bool entree_video;
// Capture vidéo
std::vector<cv::VideoCapture> video_captures;
// Fichier vidéo en cours
std::string video_fp;
// Caméra vidéo en cours
int video_idx;
// Barre d'outils
Gtk::Toolbar barre_outils;
Gtk::ToolButton b_entree, b_open, b_infos, b_exit, b_save;
// Chemin du fichier de configuration
std::string chemin_fichier_config;
// Barre d'outils
MasqueBOutils barre_outil_dessin;
int outil_dessin_en_cours;
bool sortie_en_cours;
ImageSelecteur img_selecteur;
bool video_en_cours, video_stop;
bool first_processing;
// Objets envoyés dans la fifo de calcul
struct ODEvent
{
enum
{
// Requiert la fin du thread (fin de l'application)
FIN,
// Calcul sur une image
CALCUL
} type;
OCVDemoItem *demo;
utils::model::Node modele;
};
// FIFO pour envoyer les commandes au thread de calcul
utils::hal::Fifo<ODEvent> event_fifo;
// Fin du dernier calcul demandé
utils::hal::Signal signal_calcul_termine;
int calcul_status;
// Confirmation de la terminaison du thread de calcul
utils::hal::Signal signal_thread_calcul_fin;
utils::hal::Signal signal_video_demarre,
signal_image_video_traitee,
signal_video_suspendue;
// Levé quand au moins une trame vidéo à fini d'être traitée
utils::hal::Signal signal_une_trame_traitee;
bool ignore_refresh;
};
#endif
| 7,934
|
C++
|
.h
| 235
| 30.2
| 79
| 0.718474
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,053
|
ocvdemo-item.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/ocvdemo-item.hpp
|
/** @file ocv-demo-item.hpp
* @brief Classe de base pour toutes les démonstrations
*
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef OCVDEMO_ITEM_HPP
#define OCVDEMO_ITEM_HPP
#include "cutil.hpp"
#include "modele.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#ifdef WIN
//#define USE_CONTRIB
#endif
using namespace cv;
using namespace utils::model;
struct OCVDemoItemRefresh {};
////////////////////////////////////////////////////////////////////////////
/** @bref Classe de base pour toutes les démonstrations OpenCV */
/** @brief Base class for all OpenCV demonstrations */
class OCVDemoItem: public utils::CProvider<OCVDemoItemRefresh>
{
public:
/** @bref Propriétés d'une démonstration OpenCV */
/** @brief Properties of an OpenCV demonstration */
struct OCVDemoItemProperties
{
/** Chaine d'identification (pour retrouver le schéma XML) */
std::string id;
/** Nécessite un masque ? (exemple : inpainting) */
bool requiert_masque;
/** Nécessite la sélection d'une région d'intérêt ? */
bool requiert_roi;
/** Minimum number of input images for this demo.
* Default is 1 (needs at least one image). */
int input_min;
/** Maximum number of input images for this demo.
* -1 means "not specified" (e.g. accept arbitrary number of images). */
int input_max;
bool preserve_ratio_aspet;
};
/** Réglages d'une démonstration OpenCV */
struct OCVDemoItemInput
{
/** Modèle (configuration du traitement) */
utils::model::Node model;
/** Si oui, rectangle définissant la ROI */
cv::Rect roi;
/** Si oui, valeur du masque */
cv::Mat mask;
/** Liste des images d'entrée */
/** List of input images */
std::vector<Mat> images;
};
/** Sortie */
/** @brief Output */
struct OCVDemoItemOutput
{
/** Nombre d'images produites */
/** @brief Number of output images */
int nout;
# define DEMO_MAX_IMG_OUT 50
/** Images de sortie */
/** @brief Output images */
cv::Mat images[DEMO_MAX_IMG_OUT];
/** Nom des différentes images de sortie */
/** @brief Names of the output images (UTF-8) */
std::string names[DEMO_MAX_IMG_OUT];
/** Message d'erreur si échec */
/** Error message in case of failure (UTF-8) */
std::string errmsg;
/** TO DEPRECATE? Pointeur vers la "vraie" image de sortie ???? to remove !!!! */
// cv::Mat vrai_sortie;
};
/** Propriétés de la démo */
OCVDemoItemProperties props;
/** Réglages de la démo */
OCVDemoItemInput input;
/** Résultat de l'exécution de la démo */
OCVDemoItemOutput output;
/** Calcul effectif */
/** @brief Overload this method to define the specific processing to be done for this demo */
virtual int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output) = 0;
/** Constructeur par défaut */
OCVDemoItem();
/** Destructeur */
virtual ~OCVDemoItem(){}
/** Appelé dès lors que la ROI a changé */
virtual void set_roi(const cv::Mat &I, const cv::Rect &new_roi){input.roi = new_roi;}
/** Evenement souris */
virtual void on_mouse(int x, int y, int evt, int wnd) {};
/** Demande de remise à zéro de l'état de la démo */
virtual void raz() {};
utils::model::Node modele;
};
#endif /* OCVDEMO_ITEM_HPP_ */
| 4,184
|
C++
|
.h
| 110
| 33.890909
| 95
| 0.67968
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,054
|
boutils-image.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/tools/boutils-image.hpp
|
/**
* Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
*/
#ifndef BOUTILS_IMAGE_HPP
#define BOUTILS_IMAGE_HPP
#include "mmi/stdview.hpp"
////////////////////////////////////////////////////////////////////////////
/** @brief Barre d'outil pour le choix d'un outil (gomme, pinceau, ...) */
class MasqueBOutils
{
public:
/** Constructeur */
MasqueBOutils();
/** Montre la barre d'outils */
void montre();
/** Cache la barre d'outils */
void cache();
/** Mise à jour de la langue */
void maj_lang();
private:
Gtk::VBox vbox;
Gtk::Window wnd;
Gtk::Toolbar tools;
Gtk::ToolButton b_raz;
Gtk::ToggleToolButton b_gomme, b_remplissage;
friend class OCVDemo;
};
#endif
| 782
|
C++
|
.h
| 29
| 24.275862
| 76
| 0.621951
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,055
|
image-selecteur.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/tools/image-selecteur.hpp
|
/** @file image-selecteur.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef IMAGE_SELECTOR_HPP
#define IMAGE_SELECTOR_HPP
#include "mmi/gtkutil.hpp"
#include <gdkmm/pixbuf.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "cutil.hpp"
#include "mmi/stdview.hpp"
struct ImageSelecteurRefresh{};
/** @brief Sélecteur d'image */
class ImageSelecteur:
public Gtk::Window,
public utils::CProvider<ImageSelecteurRefresh>
{
public:
ImageSelecteur();
void maj_langue();
void maj_actif();
void ajoute_fichier(std::string s);
void raz();
void get_list(std::vector<cv::Mat> &list);
unsigned int get_nb_images() const;
bool has_video();
void get_video_list(std::vector<std::string> &list);
struct SpecEntree
{
enum{TYPE_IMG, TYPE_VIDEO, TYPE_WEBCAM} type;
bool is_video(){return (type == TYPE_WEBCAM) || (type == TYPE_VIDEO);}
std::string chemin;
unsigned int id_webcam;
cv::Mat img;
};
void get_entrees(std::vector<SpecEntree> &liste);
int nmin, nmax;
private:
void set_fichier(int idx, std::string s);
std::string media_open_dialog(utils::model::Node mod);
void on_size_change(Gtk::Allocation &alloc);
bool on_b_pressed(GdkEventButton *event);
bool on_b_released(GdkEventButton *event);
bool on_k_released(GdkEventKey *event);
void on_b_open();
void on_b_add();
void on_b_del();
void on_b_del_tout();
void on_b_maj();
void on_dropped_file(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time);
void maj_mosaique();
void maj_selection();
void maj_has_video();
Gtk::Image gtk_image;
Gtk::EventBox evt_box;
Glib::RefPtr<Gdk::Pixbuf> pixbuf;
Gtk::VBox vbox;
Gtk::ToolButton b_suppr, b_open, b_suppr_tout, b_maj, b_ajout;
Gtk::Toolbar toolbar;
bool toolbar_est_pleine; // En ce moment, a les boutons b_suppr, b_suppr_tout et b_add ?
cv::Mat bigmat;
struct Image
{
SpecEntree spec;
std::string /*fichier,*/ nom;
//cv::Mat mat;
unsigned int ix, iy, px, py;
utils::model::Node modele; // Modèle de source
};
unsigned int ncols, nrows, col_width, row_height;
unsigned int img_width, img_height;
std::deque<Image> images;
int csel;
bool has_a_video;
friend class OCVDemo;
};
#endif
| 3,132
|
C++
|
.h
| 89
| 31.651685
| 150
| 0.717608
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,056
|
image-mosaique.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/tools/image-mosaique.hpp
|
/** @file image-mosaique.hpp
* @brief Fenêtre de sortie
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef IMAGE_MOSAIQUE_HPP
#define IMAGE_MOSAIQUE_HPP
#include "opencv2/imgproc/imgproc.hpp"
#include "cutil.hpp"
#include <string>
/** Evenement souris sur la fenêtre d'affichage */
struct OCVMouseEvent
{
// Numéro d'image surlaquelle l'utilisateur a cliqué
int image;
// Code évenement souris
int event;
// Position dans la sous-fenêtre concernée
int x, y;
int flags;
};
////////////////////////////////////////////////////////////////////////////
/** @brief Fenêtre afficher un ou plusieurs images
* (utilisé pour afficher les résultats des traitements)
* @todo Réécrire à base de fenêtre GTK. */
class ImageMosaique: public utils::CProvider<OCVMouseEvent>
{
public:
/** Constructeur */
ImageMosaique();
/** Affichage de plusieurs images */
int show_multiple_images(std::string title,
std::vector<cv::Mat> lst,
std::vector<std::string> titles);
/** Mise à jour d'une image en particulier */
void update_image(int index, const cv::Mat &img);
void mouse_callback(int event, int x, int y, int flags);
/** Devrait être privé ! */
bool callback_init_ok;
/** Retourne l'image globale */
cv::Mat get_global_img(){return disp_img;}
bool preserve_ratio_aspet;
private:
/** Image globale */
cv::Mat disp_img;
/** Position de chaque image */
std::vector<cv::Rect> img_pos;
/** Dimension de chaque image */
std::vector<cv::Size> img_sizes;
/** Titre principal */
std::string title;
utils::hal::Mutex mutex;
};
#endif
| 2,470
|
C++
|
.h
| 65
| 33.415385
| 86
| 0.680761
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,057
|
reco-demo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/reco-demo.hpp
|
/** @file reco-demo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef RECO_DEMO_HPP_
#define RECO_DEMO_HPP_
#include "ocvdemo-item.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/features2d/features2d.hpp"
class MatchDemo: public OCVDemoItem
{
public:
MatchDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
//void setup_model(Node &model);
private:
bool lock;
std::vector<cv::Mat> imgs;
};
class PanoDemo: public OCVDemoItem
{
public:
PanoDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
bool lock;
};
class CornerDemo: public OCVDemoItem
{
public:
CornerDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
};
class ScoreShiTomasi: public OCVDemoItem
{
public:
ScoreShiTomasi();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
};
class VisageDemo: public OCVDemoItem
{
public:
VisageDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
CascadeClassifier face_cascade, eyes_cascade;
RNG rng;
};
class CascGenDemo: public OCVDemoItem
{
public:
CascGenDemo(std::string id);
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
std::vector<std::string> cnames;
CascadeClassifier cascade[3];
RNG rng;
bool cascade_ok;
};
class DemoHog: public OCVDemoItem
{
public:
DemoHog();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoFaceRecognizer: public OCVDemoItem
{
public:
DemoFaceRecognizer();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif /* MORPHO_DEMO_HPP_ */
| 2,452
|
C++
|
.h
| 85
| 26.364706
| 79
| 0.775362
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,058
|
ocr.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/ocr.hpp
|
/** @file ocr.hpp
Copyright 2017 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef OCR_DEMO_HPP
#define OCR_DEMO_HPP
#include "ocvdemo-item.hpp"
/****************************************/
/** @brief Stereo calibration demonstration (from previously captured image pairs) */
class DemoOCR: public OCVDemoItem
{
public:
DemoOCR();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,188
|
C++
|
.h
| 27
| 40.37037
| 85
| 0.72973
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,059
|
fourier-demo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/fourier-demo.hpp
|
#ifndef FOURIER_DEMO_H
#define FOURIER_DEMO_H
#include "ocvdemo-item.hpp"
class DFTDemo: public OCVDemoItem
{
public:
DFTDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class IFTDemo: public OCVDemoItem
{
public:
IFTDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoSousSpectrale: public OCVDemoItem
{
public:
DemoSousSpectrale();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoDetectionRotation: public OCVDemoItem
{
public:
DemoDetectionRotation();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoDetectionTranslation: public OCVDemoItem
{
public:
DemoDetectionTranslation();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoDetectionPeriode: public OCVDemoItem
{
public:
DemoDetectionPeriode();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 961
|
C++
|
.h
| 40
| 22.175
| 66
| 0.81888
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,060
|
morpho-demo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/morpho-demo.hpp
|
/** @file morpho-demo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef MORPHO_DEMO_HPP_
#define MORPHO_DEMO_HPP_
#include "ocvdemo-item.hpp"
class MorphoDemo: public OCVDemoItem
{
public:
MorphoDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoSqueletisation: public OCVDemoItem
{
public:
DemoSqueletisation();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif /* MORPHO_DEMO_HPP_ */
| 1,250
|
C++
|
.h
| 31
| 37
| 79
| 0.761589
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,061
|
demo-skeleton.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/demo-skeleton.hpp
|
/** @file demo-skeleton.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef SKEKETON_DEMO_HPP
#define SKELETON_DEMO_HPP
#include "ocvdemo-item.hpp"
//for new demo change SkeletonDemo to your class name
class SkeletonDemo: public OCVDemoItem
{
public:
SkeletonDemo()
{
props.id = "skeleton";
}
public:
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,198
|
C++
|
.h
| 30
| 35.866667
| 79
| 0.753712
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,062
|
histo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/histo.hpp
|
/** @file histo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef HISTO_HPP_
#define HISTO_HPP_
#include "ocvdemo-item.hpp"
extern int calc_hist(const cv::Mat &I, cv::Rect &roi, cv::MatND &hist);
extern int calc_bp(const cv::Mat &I, cv::Rect &roi, cv::MatND &backproj);
extern int calc_bp(const cv::Mat &I, const cv::MatND &hist, cv::MatND &backproj);
// Egalisation d'histogramme
class HistoEgalisationDemo: public OCVDemoItem
{
public:
HistoEgalisationDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class HistoCalc: public OCVDemoItem
{
public:
HistoCalc();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
// Backprojection
class HistoBP: public OCVDemoItem
{
public:
HistoBP();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif /* MORPHO_DEMO_HPP_ */
| 1,641
|
C++
|
.h
| 42
| 36.142857
| 81
| 0.754896
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,063
|
video-demo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/video-demo.hpp
|
/** @file video-demo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef OPTFLOWDEMO_HPP
#define OPTFLOWDEMO_HPP
#include "ocvdemo-item.hpp"
#include "opencv2/video/video.hpp"
/** @brief Démonstration flux optique */
class OptFlowDemo: public OCVDemoItem
{
public:
OptFlowDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
cv::Mat Iprec;
bool reset;
cv::Ptr<cv::DenseOpticalFlow> algo;
};
/** @brief Démonstration soustraction d'arrière-plan */
class SousArrierePlanDemo: public OCVDemoItem
{
public:
SousArrierePlanDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
//cv::BackgroundSubtractorMOG mog;
Ptr<cv::BackgroundSubtractor> algo;
Mat mhi;
int nframes;
int osel;
void update_sel(int nsel);
};
/** Démonstration algorithme camshift */
class CamShiftDemo: public OCVDemoItem
{
public:
CamShiftDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
void set_roi(const cv::Mat &I, const cv::Rect &new_roi);
private:
cv::MatND hist;
cv::Rect trackwindow;
bool bp_init_ok;
};
class DemoVideoStab: public OCVDemoItem
{
public:
DemoVideoStab();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 2,042
|
C++
|
.h
| 63
| 29.619048
| 79
| 0.764916
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,064
|
3d.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/3d.hpp
|
/** @file 3d.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef CAM_DEMO_HPP
#define CAM_DEMO_HPP
#include "ocvdemo-item.hpp"
/** @brief Résultat de la calibration stéréo */
struct StereoCalResultats
{
/** Calibration effectuée avec succès oui / non */
bool valide;
/** Paramètres intrinséques de chaque caméra */
cv::Mat matrices_cameras[2];
/** Paramètres de distortion (correction des non linéarités de chaque caméra) */
cv::Mat dcoefs[2];
/** Rotation (R: 3x3) et translation (T: 3x1) entre les 2 caméras */
cv::Mat R, T;
/** Matrice essentielle */
cv::Mat E;
/** Matrice fondamentale */
cv::Mat F;
/** Matrices de projection 3x4 vers le système de coordonnées rectifié */
cv::Mat rectif_P[2];
/** Transformées de rectification 3x3 (matrices de rotation) */
cv::Mat rectif_R[2];
/** LUTs (x,y) pour la fonction remap (rectification) */
cv::Mat rmap[2][2];
/** Matrice 4x4 de mapping disparité vers profondeur */
cv::Mat Q;
};
extern StereoCalResultats stereo_cal;
/****************************************/
/** @brief Stereo calibration demonstration (from previously captured image pairs) */
class StereoCalDemo: public OCVDemoItem
{
public:
StereoCalDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
int lookup_corners(cv::Mat &I,
cv::Mat &O,
utils::model::Node &model,
std::vector<cv::Point2f> &coins);
static StereoCalDemo *get_instance();
private:
static StereoCalDemo *instance;
};
/** @brief Recherche de matrice fondamentale à partir des points d'intérêts */
class StereoFMatDemo: public OCVDemoItem
{
StereoFMatDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/****************************************/
/** @brief Stereo calibration demonstration (interactive calibration from live video) */
class StereoCalLiveDemo: public OCVDemoItem
{
public:
StereoCalLiveDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
std::vector<std::vector<cv::Point2f>> pairs;
};
/****************************************/
/** @brief Rectification demonstration */
class RectificationDemo: public OCVDemoItem
{
public:
RectificationDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/****************************************/
/** @brief Epipolar lines demonstration */
class EpiDemo: public OCVDemoItem
{
public:
EpiDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
void on_mouse(int x, int y, int evt, int wnd);
void raz();
private:
std::vector<cv::Point2f> points[2];
};
/***************************************/
/** @brief Disparity map demonstration
* Compute the disparity map between 2 rectified images. */
class DispMapDemo: public OCVDemoItem
{
public:
DispMapDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/********************************************/
/** @brief Camera calibration demonstration
* Detect a chessboard, and correct camera distortions. */
class CamCalDemo: public OCVDemoItem
{
public:
CamCalDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/********************************************/
/** @brief Localisation en 3D d'une balle à partir
* d'une caméra stéréo. */
class DemoLocalisation3D: public OCVDemoItem
{
public:
DemoLocalisation3D();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 4,322
|
C++
|
.h
| 122
| 32.213115
| 88
| 0.687545
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,065
|
appauto.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/appauto.hpp
|
/** @file appauto.hpp
Copyright 2016 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef APPAUTO_DEMO_HPP
#define APPAUTO_DEMO_HPP
#include "ocvdemo-item.hpp"
class DemoAppAuto: public OCVDemoItem
{
public:
DemoAppAuto();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,076
|
C++
|
.h
| 25
| 39.32
| 79
| 0.759615
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,066
|
filtrage.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/filtrage.hpp
|
/** @file filtrage.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef FILTRAGE_DEMO_HPP
#define FILTRAGE_DEMO_HPP
#include "ocvdemo-item.hpp"
/** Configuration filtrage */
struct DemoFiltrageConfig
{
bool bruit_blanc_actif;
float sigma_bb;
bool poivre_et_sel_actif;
float sigma_ps;
float p_ps;
typedef enum
{
FILTRE_MA = 0,
FILTRE_GAUSSIEN = 1,
FILTRE_MEDIAN = 2,
FILTRE_BILATERAL = 3
} filtre_t;
filtre_t type_filtre;
struct
{
int taille_noyau;
} ma;
struct
{
int taille_noyau;
float sigma;
} gaussien;
struct
{
int taille_noyau;
} median;
struct
{
int taille_noyau;
float sigma_couleur, sigma_espace;
} bilateral;
};
class DemoFiltrage: public OCVDemoItem
{
public:
DemoFiltrage();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
int proceed(const DemoFiltrageConfig &conf, cv::Mat &I, OCVDemoItemOutput &output);
};
class DemoRedim: public OCVDemoItem
{
public:
DemoRedim();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoFiltreGabor: public OCVDemoItem
{
public:
DemoFiltreGabor();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 2,036
|
C++
|
.h
| 74
| 24.189189
| 85
| 0.735946
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,067
|
photographie.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/photographie.hpp
|
/** @file photographie.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef PHOTO_HPP
#define PHOTO_HPP
#include "ocvdemo-item.hpp"
class HDRDemo: public OCVDemoItem
{
public:
HDRDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,059
|
C++
|
.h
| 25
| 38.64
| 79
| 0.757576
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,068
|
seuillage.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/seuillage.hpp
|
/** @file seuillage.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef SEUILLAGE_HPP
#define SEUILLAGE_HPP
#include "ocvdemo-item.hpp"
/** @brief Démonstration réparation d'image */
class InpaintDemo: public OCVDemoItem
{
public:
InpaintDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
private:
};
/** @brief Démonstration seuillage */
class Seuillage: public OCVDemoItem
{
public:
Seuillage();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/** @brief Démonstration transformée de distance */
class DTransDemo: public OCVDemoItem
{
public:
DTransDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,495
|
C++
|
.h
| 41
| 33.292683
| 79
| 0.767133
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,069
|
segmentation.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/segmentation.hpp
|
/** @file segmentation.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef SEGM_HPP
#define SEGM_HPP
#include "ocvdemo-item.hpp"
/** @brief Démonstration réparation d'image */
class DemoMahalanobis: public OCVDemoItem
{
public:
DemoMahalanobis();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/** @brief Démonstration algorithme grabcut */
class GrabCutDemo: public OCVDemoItem
{
public:
GrabCutDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/** @brief Démonstration algorithme watershed */
class WShedDemo: public OCVDemoItem
{
public:
WShedDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
/** @brief Démonstration réparation d'image */
class DemoSuperpixels: public OCVDemoItem
{
public:
DemoSuperpixels();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,682
|
C++
|
.h
| 47
| 32.87234
| 79
| 0.771375
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,070
|
gradient-demo.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/gradient-demo.hpp
|
/** @file gradient-demo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef GRADIENT_DEMO_HPP_
#define GRADIENT_DEMO_HPP_
#include "ocvdemo-item.hpp"
class NetDemo: public OCVDemoItem
{
public:
NetDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class GradientDemo: public OCVDemoItem
{
public:
GradientDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class LaplaceDemo: public OCVDemoItem
{
public:
LaplaceDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DetFlouDemo: public OCVDemoItem
{
public:
DetFlouDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class CannyDemo: public OCVDemoItem
{
public:
CannyDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class ContourDemo: public OCVDemoItem
{
public:
ContourDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class HoughDemo: public OCVDemoItem
{
public:
HoughDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class HoughCDemo: public OCVDemoItem
{
public:
HoughCDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class RectDemo: public OCVDemoItem
{
public:
RectDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif /* MORPHO_DEMO_HPP_ */
| 2,174
|
C++
|
.h
| 73
| 27.315068
| 79
| 0.777724
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,071
|
espaces-de-couleurs.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/espaces-de-couleurs.hpp
|
/** @file color-demo.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef COLOR_DEMO_HPP
#define COLOR_DEMO_HPP
#include "ocvdemo-item.hpp"
class HSVDemo: public OCVDemoItem
{
public:
HSVDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
class DemoBalleTennis: public OCVDemoItem
{
public:
DemoBalleTennis();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,211
|
C++
|
.h
| 31
| 35.709677
| 79
| 0.763699
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,072
|
misc.hpp
|
tsdconseil_opencv-demonstrator/ocvdemo/include/demo-items/misc.hpp
|
/** @file demo-skeleton.hpp
Copyright 2015 J.A. / http://www.tsdconseil.fr
Project web page: http://www.tsdconseil.fr/log/opencv/demo/index-en.html
This file is part of OCVDemo.
OCVDemo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCVDemo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OCVDemo. If not, see <http://www.gnu.org/licenses/>.
**/
#ifndef MISC_HPP
#define MISC_HPP
#include "ocvdemo-item.hpp"
// Replace "MyDemo" by the name of your class
class CameraDemo: public OCVDemoItem
{
public:
CameraDemo();
int proceed(OCVDemoItemInput &input, OCVDemoItemOutput &output);
};
#endif
| 1,111
|
C++
|
.h
| 26
| 39.076923
| 79
| 0.756757
|
tsdconseil/opencv-demonstrator
| 141
| 57
| 16
|
LGPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,074
|
PS2KeyTable.h
|
techpaul_PS2KeyAdvanced/src/PS2KeyTable.h
|
/* Version V1.0.8
PS2KeyTable.h - PS2KeyAdvanced library keycode values to return values
Copyright (c) 2007 Free Software Foundation. All right reserved.
Written by Paul Carpenter, PC Services <sales@pcserviceselectronics.co.uk>
Created September 2014
V1.0.2 Updated January 2016 - Paul Carpenter - add tested on Due and tidy ups for V1.5 Library Management
PRIVATE to library
Test History
September 2014 Uno and Mega 2560 September 2014 using Arduino V1.6.0
January 2016 Uno, Mega 2560 and Due using Arduino 1.6.7 and Due Board
Manager V1.6.6
Internal to library private tables
(may disappear in updates do not rely on this file or definitions)
This is for a LATIN style keyboard. Will support most keyboards even ones
with multimedia keys or even 24 function keys.
Definitions used for key codes from a PS2 keyboard, do not use in your
code these are handled by the library.
See PS2KeyAdvanced.h for codes returned from library and flag settings
Two sets of tables
Single Byte codes returned as key codes
Two byte Codes preceded by E0 code returned as keycodes
Same tables used for make and break decode
Special cases are -
PRTSCR that ignores one of the sequences (E0,12) as this is not always sent
especially with modifier keys or some keyboards when typematic repeat comes on.
PAUSE as this is an 8 byte sequence only one starting E1 so main code gets E1
and waits for 7 more valid bytes to make the coding.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PS2KeyTable_h
#define PS2KeyTable_h
/* Table contents are pairs of numbers
first code from keyboard
second is either PS2_KEY_IGNOPRE code or key code to return
Single byte Key table
In codes can only be 1 - 0x9F, plus 0xF2 and 0xF1
Out Codes in range 1 to 0x9F
*/
#if defined(PS2_REQUIRES_PROGMEM)
const uint8_t PROGMEM single_key[][ 2 ] = {
#else
const uint8_t single_key[][ 2 ] = {
#endif
{ PS2_KC_NUM, PS2_KEY_NUM },
{ PS2_KC_SCROLL, PS2_KEY_SCROLL },
{ PS2_KC_CAPS, PS2_KEY_CAPS },
{ PS2_KC_L_SHIFT, PS2_KEY_L_SHIFT },
{ PS2_KC_R_SHIFT, PS2_KEY_R_SHIFT },
{ PS2_KC_CTRL, PS2_KEY_L_CTRL },
{ PS2_KC_ALT, PS2_KEY_L_ALT },
{ PS2_KC_SYSRQ, PS2_KEY_SYSRQ },
{ PS2_KC_ESC, PS2_KEY_ESC },
{ PS2_KC_BS, PS2_KEY_BS },
{ PS2_KC_TAB, PS2_KEY_TAB },
{ PS2_KC_ENTER, PS2_KEY_ENTER },
{ PS2_KC_SPACE, PS2_KEY_SPACE },
{ PS2_KC_KP0, PS2_KEY_KP0 },
{ PS2_KC_KP1, PS2_KEY_KP1 },
{ PS2_KC_KP2, PS2_KEY_KP2 },
{ PS2_KC_KP3, PS2_KEY_KP3 },
{ PS2_KC_KP4, PS2_KEY_KP4 },
{ PS2_KC_KP5, PS2_KEY_KP5 },
{ PS2_KC_KP6, PS2_KEY_KP6 },
{ PS2_KC_KP7, PS2_KEY_KP7 },
{ PS2_KC_KP8, PS2_KEY_KP8 },
{ PS2_KC_KP9, PS2_KEY_KP9 },
{ PS2_KC_KP_DOT, PS2_KEY_KP_DOT },
{ PS2_KC_KP_PLUS, PS2_KEY_KP_PLUS },
{ PS2_KC_KP_MINUS, PS2_KEY_KP_MINUS },
{ PS2_KC_KP_TIMES, PS2_KEY_KP_TIMES },
{ PS2_KC_KP_EQUAL, PS2_KEY_KP_EQUAL },
{ PS2_KC_0, PS2_KEY_0 },
{ PS2_KC_1, PS2_KEY_1 },
{ PS2_KC_2, PS2_KEY_2 },
{ PS2_KC_3, PS2_KEY_3 },
{ PS2_KC_4, PS2_KEY_4 },
{ PS2_KC_5, PS2_KEY_5 },
{ PS2_KC_6, PS2_KEY_6 },
{ PS2_KC_7, PS2_KEY_7 },
{ PS2_KC_8, PS2_KEY_8 },
{ PS2_KC_9, PS2_KEY_9 },
{ PS2_KC_APOS, PS2_KEY_APOS },
{ PS2_KC_COMMA, PS2_KEY_COMMA },
{ PS2_KC_MINUS, PS2_KEY_MINUS },
{ PS2_KC_DOT, PS2_KEY_DOT },
{ PS2_KC_DIV, PS2_KEY_DIV },
{ PS2_KC_SINGLE, PS2_KEY_SINGLE },
{ PS2_KC_A, PS2_KEY_A },
{ PS2_KC_B, PS2_KEY_B },
{ PS2_KC_C, PS2_KEY_C },
{ PS2_KC_D, PS2_KEY_D },
{ PS2_KC_E, PS2_KEY_E },
{ PS2_KC_F, PS2_KEY_F },
{ PS2_KC_G, PS2_KEY_G },
{ PS2_KC_H, PS2_KEY_H },
{ PS2_KC_I, PS2_KEY_I },
{ PS2_KC_J, PS2_KEY_J },
{ PS2_KC_K, PS2_KEY_K },
{ PS2_KC_L, PS2_KEY_L },
{ PS2_KC_M, PS2_KEY_M },
{ PS2_KC_N, PS2_KEY_N },
{ PS2_KC_O, PS2_KEY_O },
{ PS2_KC_P, PS2_KEY_P },
{ PS2_KC_Q, PS2_KEY_Q },
{ PS2_KC_R, PS2_KEY_R },
{ PS2_KC_S, PS2_KEY_S },
{ PS2_KC_T, PS2_KEY_T },
{ PS2_KC_U, PS2_KEY_U },
{ PS2_KC_V, PS2_KEY_V },
{ PS2_KC_W, PS2_KEY_W },
{ PS2_KC_X, PS2_KEY_X },
{ PS2_KC_Y, PS2_KEY_Y },
{ PS2_KC_Z, PS2_KEY_Z },
{ PS2_KC_SEMI, PS2_KEY_SEMI },
{ PS2_KC_BACK, PS2_KEY_BACK },
{ PS2_KC_OPEN_SQ, PS2_KEY_OPEN_SQ },
{ PS2_KC_CLOSE_SQ, PS2_KEY_CLOSE_SQ },
{ PS2_KC_EQUAL, PS2_KEY_EQUAL },
{ PS2_KC_EUROPE2, PS2_KEY_EUROPE2 },
{ PS2_KC_F1, PS2_KEY_F1 },
{ PS2_KC_F2, PS2_KEY_F2 },
{ PS2_KC_F3, PS2_KEY_F3 },
{ PS2_KC_F4, PS2_KEY_F4 },
{ PS2_KC_F5, PS2_KEY_F5 },
{ PS2_KC_F6, PS2_KEY_F6 },
{ PS2_KC_F7, PS2_KEY_F7 },
{ PS2_KC_F8, PS2_KEY_F8 },
{ PS2_KC_F9, PS2_KEY_F9 },
{ PS2_KC_F10, PS2_KEY_F10 },
{ PS2_KC_F11, PS2_KEY_F11 },
{ PS2_KC_F12, PS2_KEY_F12 },
{ PS2_KC_F13, PS2_KEY_F13 },
{ PS2_KC_F14, PS2_KEY_F14 },
{ PS2_KC_F15, PS2_KEY_F15 },
{ PS2_KC_F16, PS2_KEY_F16 },
{ PS2_KC_F17, PS2_KEY_F17 },
{ PS2_KC_F18, PS2_KEY_F18 },
{ PS2_KC_F19, PS2_KEY_F19 },
{ PS2_KC_F20, PS2_KEY_F20 },
{ PS2_KC_F21, PS2_KEY_F21 },
{ PS2_KC_F22, PS2_KEY_F22 },
{ PS2_KC_F23, PS2_KEY_F23 },
{ PS2_KC_F24, PS2_KEY_F24 },
{ PS2_KC_KP_COMMA, PS2_KEY_KP_COMMA },
{ PS2_KC_INTL1, PS2_KEY_INTL1 },
{ PS2_KC_INTL2, PS2_KEY_INTL2 },
{ PS2_KC_INTL3, PS2_KEY_INTL3 },
{ PS2_KC_INTL4, PS2_KEY_INTL4 },
{ PS2_KC_INTL5, PS2_KEY_INTL5 },
{ PS2_KC_LANG1, PS2_KEY_LANG1 },
{ PS2_KC_LANG2, PS2_KEY_LANG2 },
{ PS2_KC_LANG3, PS2_KEY_LANG3 },
{ PS2_KC_LANG4, PS2_KEY_LANG4 },
{ PS2_KC_LANG5, PS2_KEY_LANG5 }
};
/* Two byte Key table after an E0 byte received */
#if defined(PS2_REQUIRES_PROGMEM)
const uint8_t PROGMEM extended_key[][ 2 ] = {
#else
const uint8_t extended_key[][ 2 ] = {
#endif
{ PS2_KC_IGNORE, PS2_KEY_IGNORE },
{ PS2_KC_PRTSCR, PS2_KEY_PRTSCR },
{ PS2_KC_CTRL, PS2_KEY_R_CTRL },
{ PS2_KC_ALT, PS2_KEY_R_ALT },
{ PS2_KC_L_GUI, PS2_KEY_L_GUI },
{ PS2_KC_R_GUI, PS2_KEY_R_GUI },
{ PS2_KC_MENU, PS2_KEY_MENU },
{ PS2_KC_BREAK, PS2_KEY_BREAK },
{ PS2_KC_HOME, PS2_KEY_HOME },
{ PS2_KC_END, PS2_KEY_END },
{ PS2_KC_PGUP, PS2_KEY_PGUP },
{ PS2_KC_PGDN, PS2_KEY_PGDN },
{ PS2_KC_L_ARROW, PS2_KEY_L_ARROW },
{ PS2_KC_R_ARROW, PS2_KEY_R_ARROW },
{ PS2_KC_UP_ARROW, PS2_KEY_UP_ARROW },
{ PS2_KC_DN_ARROW, PS2_KEY_DN_ARROW },
{ PS2_KC_INSERT, PS2_KEY_INSERT },
{ PS2_KC_DELETE, PS2_KEY_DELETE },
{ PS2_KC_KP_ENTER, PS2_KEY_KP_ENTER },
{ PS2_KC_KP_DIV, PS2_KEY_KP_DIV },
{ PS2_KC_NEXT_TR, PS2_KEY_NEXT_TR },
{ PS2_KC_PREV_TR, PS2_KEY_PREV_TR },
{ PS2_KC_STOP, PS2_KEY_STOP },
{ PS2_KC_PLAY, PS2_KEY_PLAY },
{ PS2_KC_MUTE, PS2_KEY_MUTE },
{ PS2_KC_VOL_UP, PS2_KEY_VOL_UP },
{ PS2_KC_VOL_DN, PS2_KEY_VOL_DN },
{ PS2_KC_MEDIA, PS2_KEY_MEDIA },
{ PS2_KC_EMAIL, PS2_KEY_EMAIL },
{ PS2_KC_CALC, PS2_KEY_CALC },
{ PS2_KC_COMPUTER, PS2_KEY_COMPUTER },
{ PS2_KC_WEB_SEARCH, PS2_KEY_WEB_SEARCH },
{ PS2_KC_WEB_HOME, PS2_KEY_WEB_HOME },
{ PS2_KC_WEB_BACK, PS2_KEY_WEB_BACK },
{ PS2_KC_WEB_FORWARD, PS2_KEY_WEB_FORWARD },
{ PS2_KC_WEB_STOP, PS2_KEY_WEB_STOP },
{ PS2_KC_WEB_REFRESH, PS2_KEY_WEB_REFRESH },
{ PS2_KC_WEB_FAVOR, PS2_KEY_WEB_FAVOR },
{ PS2_KC_POWER, PS2_KEY_POWER },
{ PS2_KC_SLEEP, PS2_KEY_SLEEP },
{ PS2_KC_WAKE, PS2_KEY_WAKE }
};
/* Scroll lock numeric keypad re-mappings for NOT NUMLOCK */
/* in translated code order order is important */
#if defined(PS2_REQUIRES_PROGMEM)
const uint8_t PROGMEM scroll_remap[] = {
#else
const uint8_t scroll_remap[] = {
#endif
PS2_KEY_INSERT, // PS2_KEY_KP0
PS2_KEY_END, // PS2_KEY_KP1
PS2_KEY_DN_ARROW, // PS2_KEY_KP2
PS2_KEY_PGDN, // PS2_KEY_KP3
PS2_KEY_L_ARROW, // PS2_KEY_KP4
PS2_KEY_IGNORE, // PS2_KEY_KP5
PS2_KEY_R_ARROW, // PS2_KEY_KP6
PS2_KEY_HOME, // PS2_KEY_KP7
PS2_KEY_UP_ARROW, // PS2_KEY_KP8
PS2_KEY_PGUP, // PS2_KEY_KP9
PS2_KEY_DELETE // PS2_KEY_KP_DOT
};
#endif
| 10,825
|
C++
|
.h
| 233
| 33.407725
| 107
| 0.502649
|
techpaul/PS2KeyAdvanced
| 139
| 27
| 7
|
LGPL-2.1
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,076
|
PS2KeyCode.h
|
techpaul_PS2KeyAdvanced/src/PS2KeyCode.h
|
/* Version V1.0.8
PS2KeyCode.h - PS2KeyAdvanced library Internal actual PS2 key code sequences
Copyright (c) 2007 Free Software Foundation. All right reserved.
Written by Paul Carpenter, PC Services <sales@pcserviceselectronics.co.uk>
Created September 2014
Updated January 2016 - Paul Carpenter - add tested on Due and tidy ups for V1.5 Library Management
Updated December 2019 - Paul Carpenter - Fix typo in code for Multimedia STOP
PRIVATE to library
Test History
September 2014 Uno and Mega 2560 September 2014 using Arduino V1.6.0
January 2016 Uno, Mega 2560 and Due using Arduino 1.6.7 and Due Board
Manager V1.6.6
This is for a LATIN style keyboard. Will support most keyboards even ones
with multimedia keys or even 24 function keys.
Definitions used for key codes from a PS2 keyboard, do not use in your
code these are to be handled INTERNALLY by the library.
(may disappear in updates do not rely on this file or definitions)
See PS2KeyAdvanced.h for codes returned from library and flag settings
Defines are in three groups
Special codes definition of communications bytes
Single Byte codes returned as key codes
Two byte Codes preceded by E0 code returned as keycodes
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef PS2KeyCode_h
#define PS2KeyCode_h
/* Ignore code for key code translation */
#define PS2_KEY_IGNORE 0xBB
// buffer sizes keyboard RX and TX, then key reading buffer
// Minimum size 8 can be larger
#define _RX_BUFFER_SIZE 8
// Minimum size 6 can be larger
#define _TX_BUFFER_SIZE 6
// Output Buffer of unsigned int values. Minimum size 4 can be larger
#define _KEY_BUFF_SIZE 4
/* private defines for library files not global */
/* _ps2mode status flags */
#define _PS2_BUSY 0x80
#define _TX_MODE 0x40
#define _BREAK_KEY 0x20
#define _WAIT_RESPONSE 0x10
#define _E0_MODE 0x08
#define _E1_MODE 0x04
#define _LAST_VALID 0x02
/* _tx_ready flags */
#define _HANDSHAKE 0x80
#define _COMMAND 0x01
/* Key Repeat defines */
#define _NO_BREAKS 0x08
#define _NO_REPEATS 0x80
/* PS2_keystatus byte masks (from 16 bit int masks) */
#define _BREAK ( PS2_BREAK >> 8 )
#define _SHIFT ( PS2_SHIFT >> 8 )
#define _CTRL ( PS2_CTRL >> 8 )
#define _CAPS ( PS2_CAPS >> 8 )
#define _ALT ( PS2_ALT >> 8 )
#define _ALT_GR ( PS2_ALT_GR >> 8 )
#define _GUI ( PS2_GUI >> 8 )
#define _FUNCTION ( PS2_FUNCTION >> 8 )
/* General defines of comms codes */
/* Command or response */
#define PS2_KC_RESEND 0xFE
#define PS2_KC_ACK 0xFA
#define PS2_KC_ECHO 0xEE
/* Responses */
#define PS2_KC_BAT 0xAA
// Actually buffer overrun
#define PS2_KC_OVERRUN 0xFF
// Below is general error code
#define PS2_KC_ERROR 0xFC
#define PS2_KC_KEYBREAK 0xF0
#define PS2_KC_EXTEND1 0xE1
#define PS2_KC_EXTEND 0xE0
/* Commands */
#define PS2_KC_RESET 0xFF
#define PS2_KC_DEFAULTS 0xF6
#define PS2_KC_DISABLE 0xF5
#define PS2_KC_ENABLE 0xF4
#define PS2_KC_RATE 0xF3
#define PS2_KC_READID 0xF2
#define PS2_KC_SCANCODE 0xF0
#define PS2_KC_LOCK 0xED
/* Single Byte Key Codes */
#define PS2_KC_NUM 0x77
#define PS2_KC_SCROLL 0x7E
#define PS2_KC_CAPS 0x58
#define PS2_KC_L_SHIFT 0x12
#define PS2_KC_R_SHIFT 0x59
/* This is Left CTRL and ALT but Right version is in E0 with same code */
#define PS2_KC_CTRL 0X14
#define PS2_KC_ALT 0x11
/* Generated by some keyboards by ALT and PRTSCR */
#define PS2_KC_SYSRQ 0x84
#define PS2_KC_ESC 0x76
#define PS2_KC_BS 0x66
#define PS2_KC_TAB 0x0D
#define PS2_KC_ENTER 0x5A
#define PS2_KC_SPACE 0x29
#define PS2_KC_KP0 0x70
#define PS2_KC_KP1 0x69
#define PS2_KC_KP2 0x72
#define PS2_KC_KP3 0x7A
#define PS2_KC_KP4 0x6B
#define PS2_KC_KP5 0x73
#define PS2_KC_KP6 0x74
#define PS2_KC_KP7 0x6C
#define PS2_KC_KP8 0x75
#define PS2_KC_KP9 0x7D
#define PS2_KC_KP_DOT 0x71
#define PS2_KC_KP_PLUS 0x79
#define PS2_KC_KP_MINUS 0x7B
#define PS2_KC_KP_TIMES 0x7C
/* Some keyboards have an '=' on right keypad */
#define PS2_KC_KP_EQUAL 0x0F
#define PS2_KC_0 0X45
#define PS2_KC_1 0X16
#define PS2_KC_2 0X1E
#define PS2_KC_3 0X26
#define PS2_KC_4 0X25
#define PS2_KC_5 0X2E
#define PS2_KC_6 0X36
#define PS2_KC_7 0X3D
#define PS2_KC_8 0X3E
#define PS2_KC_9 0X46
#define PS2_KC_APOS 0X52
#define PS2_KC_COMMA 0X41
#define PS2_KC_MINUS 0X4E
#define PS2_KC_DOT 0X49
#define PS2_KC_DIV 0X4A
/* Single quote or back apostrophe */
#define PS2_KC_SINGLE 0X0E
#define PS2_KC_A 0X1C
#define PS2_KC_B 0X32
#define PS2_KC_C 0X21
#define PS2_KC_D 0X23
#define PS2_KC_E 0X24
#define PS2_KC_F 0X2B
#define PS2_KC_G 0X34
#define PS2_KC_H 0X33
#define PS2_KC_I 0X43
#define PS2_KC_J 0X3B
#define PS2_KC_K 0X42
#define PS2_KC_L 0X4B
#define PS2_KC_M 0X3A
#define PS2_KC_N 0X31
#define PS2_KC_O 0X44
#define PS2_KC_P 0X4D
#define PS2_KC_Q 0X15
#define PS2_KC_R 0X2D
#define PS2_KC_S 0X1B
#define PS2_KC_T 0X2C
#define PS2_KC_U 0X3C
#define PS2_KC_V 0X2A
#define PS2_KC_W 0X1D
#define PS2_KC_X 0X22
#define PS2_KC_Y 0X35
#define PS2_KC_Z 0X1A
#define PS2_KC_SEMI 0X4C
#define PS2_KC_BACK 0X5D
// Extra key left of Z on 102 keyboards
#define PS2_KC_EUROPE2 0x61
#define PS2_KC_OPEN_SQ 0X54
#define PS2_KC_CLOSE_SQ 0X5B
#define PS2_KC_EQUAL 0X55
#define PS2_KC_F1 0X05
#define PS2_KC_F2 0X06
#define PS2_KC_F3 0X04
#define PS2_KC_F4 0X0C
#define PS2_KC_F5 0X03
#define PS2_KC_F6 0X0B
#define PS2_KC_F7 0X83
#define PS2_KC_F8 0X0A
#define PS2_KC_F9 0X01
#define PS2_KC_F10 0X09
#define PS2_KC_F11 0X78
#define PS2_KC_F12 0X07
#define PS2_KC_F13 0X08
#define PS2_KC_F14 0X10
#define PS2_KC_F15 0X18
#define PS2_KC_F16 0X20
#define PS2_KC_F17 0X28
#define PS2_KC_F18 0X30
#define PS2_KC_F19 0X38
#define PS2_KC_F20 0X40
#define PS2_KC_F21 0X48
#define PS2_KC_F22 0X50
#define PS2_KC_F23 0X57
#define PS2_KC_F24 0X5F
#define PS2_KC_KP_COMMA 0X6D
#define PS2_KC_INTL1 0X51
#define PS2_KC_INTL2 0X13
#define PS2_KC_INTL3 0X6A
#define PS2_KC_INTL4 0X64
#define PS2_KC_INTL5 0X67
#define PS2_KC_LANG1 0XF2
#define PS2_KC_LANG2 0XF1
#define PS2_KC_LANG3 0X63
#define PS2_KC_LANG4 0X62
#define PS2_KC_LANG5 0X5F
/* Extended key codes E0 table for two byte codes */
/* PS2_CTRL and PS2_ALT Need using in any table for the right keys */
/* first is special case for PRTSCR not always used so ignored by decoding */
#define PS2_KC_IGNORE 0x12
#define PS2_KC_PRTSCR 0x7C
/* Sometimes called windows key */
#define PS2_KC_L_GUI 0x1F
#define PS2_KC_R_GUI 0x27
#define PS2_KC_MENU 0x2F
/* Break is CTRL + PAUSE generated inside keyboard */
#define PS2_KC_BREAK 0x7E
#define PS2_KC_HOME 0x6C
#define PS2_KC_END 0x69
#define PS2_KC_PGUP 0x7D
#define PS2_KC_PGDN 0x7A
#define PS2_KC_L_ARROW 0x6B
#define PS2_KC_R_ARROW 0x74
#define PS2_KC_UP_ARROW 0x75
#define PS2_KC_DN_ARROW 0x72
#define PS2_KC_INSERT 0x70
#define PS2_KC_DELETE 0x71
#define PS2_KC_KP_ENTER 0x5A
#define PS2_KC_KP_DIV 0x4A
#define PS2_KC_NEXT_TR 0X4D
#define PS2_KC_PREV_TR 0X15
#define PS2_KC_STOP 0X3B
#define PS2_KC_PLAY 0X34
#define PS2_KC_MUTE 0X23
#define PS2_KC_VOL_UP 0X32
#define PS2_KC_VOL_DN 0X21
#define PS2_KC_MEDIA 0X50
#define PS2_KC_EMAIL 0X48
#define PS2_KC_CALC 0X2B
#define PS2_KC_COMPUTER 0X40
#define PS2_KC_WEB_SEARCH 0X10
#define PS2_KC_WEB_HOME 0X3A
#define PS2_KC_WEB_BACK 0X38
#define PS2_KC_WEB_FORWARD 0X30
#define PS2_KC_WEB_STOP 0X28
#define PS2_KC_WEB_REFRESH 0X20
#define PS2_KC_WEB_FAVOR 0X18
#define PS2_KC_POWER 0X37
#define PS2_KC_SLEEP 0X3F
#define PS2_KC_WAKE 0X5E
#endif
| 8,791
|
C++
|
.h
| 254
| 33.145669
| 100
| 0.698532
|
techpaul/PS2KeyAdvanced
| 139
| 27
| 7
|
LGPL-2.1
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,077
|
machineview.cpp
|
uwolfer_qtemu/machineview.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machineview.h"
#include <QUrl>
#include <QSize>
#include <QColor>
#include <QLabel>
#include <QAction>
#include <QTimer>
#include <QKeySequence>
#include <QVBoxLayout>
MachineView::MachineView(MachineConfigObject *config, QWidget *parent)
: QWidget(parent)
, view(new VncView(this))
, splash(new MachineSplash(this))
, config(config)
, fullscreenEnabled(false)
{
embeddedScrollArea = new MachineScrollArea(this);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(embeddedScrollArea);
setLayout(layout);
showSplash(true);
connect(embeddedScrollArea, SIGNAL(resized(int, int)), view, SLOT(scaleResize(int, int)));
}
MachineView::~MachineView()
{
}
void MachineView::initView()
{
showSplash(true);
delete view;
QUrl url;
url.setScheme("vnc");
if(property("vncTransport").toString() == "tcp")
{
url.setHost(property("vncHost").toString());
url.setPort(property("vncPort").toInt() + 5900);
}
else
{
QString socketLocation = property("hdd").toString();
socketLocation.replace(QRegExp("[.][^.]+$"), ".vnc");
url.setPath(socketLocation);
}
//#ifdef DEVELOPER
qDebug("connecting to:" + url.toString().toAscii());
//#endif
view = new VncView(this, url);
view->start();
showSplash(false);
connect(view, SIGNAL(changeSize(int, int)), this, SLOT(newViewSize()));
}
void MachineView::showSplash(bool show)
{
if(!show)
{
splash->hide();
embeddedScrollArea->takeWidget();
embeddedScrollArea->setWidget(view);
embeddedScrollArea->setSplashShown(false);
view->show();
}
else
{
view->hide();
embeddedScrollArea->takeWidget();
embeddedScrollArea->setWidget(splash);
embeddedScrollArea->setSplashShown(true);
splash->show();
splash->setPreview();
}
}
void MachineView::fullscreen(bool enable)
{
if(enable)
{
//entering fullscreen
showSplash(true);
fullscreenWindow = new QWidget(this, Qt::Window);
fullscreenWindow->setWindowTitle(tr("QtEmu Fullscreen") + " (" + property("name").toString() + ')');
fullscreenScrollArea = new MachineScrollArea(fullscreenWindow);
fullscreenScrollArea->setWidget(view);
fullscreenScrollArea->setProperty("scaleEmbeddedDisplay", property("scaleEmbeddedDisplay"));
connect(fullscreenScrollArea, SIGNAL(resized(int, int)), view, SLOT(scaleResize(int, int)));
QPalette palette = fullscreenScrollArea->palette();
palette.setColor(QPalette::Dark, QColor(22,22,22));
fullscreenScrollArea->setPalette(palette);
fullscreenScrollArea->setBackgroundRole(QPalette::Dark);
QVBoxLayout *fullscreenLayout = new QVBoxLayout(fullscreenWindow);
fullscreenLayout->setMargin(0);
fullscreenLayout->addWidget(fullscreenScrollArea);
MinimizePixel *minimizePixel = new MinimizePixel(fullscreenWindow);
minimizePixel->winId(); // force it to be a native widget (prevents problem with QX11EmbedContainer)
connect(minimizePixel, SIGNAL(rightClicked()), fullscreenWindow, SLOT(showMinimized()));
fullscreenWindow->setWindowFlags(Qt::Window);
fullscreenWindow->showFullScreen();
showToolBar();
captureAllKeys(true);
view->grabKeyboard();
}
else if(fullscreenEnabled)
{
//exiting fullscreen
//show();
fullscreenWindow->setWindowState(0);
fullscreenWindow->hide();
//get rid of the toolbar
config->unregisterObject(scaleAction);
toolBar->hideAndDestroy();
toolBar->deleteLater();
toolBar = 0;
fullscreenWindow->deleteLater();
fullscreenWindow = 0;
showSplash(false);
}
fullscreenEnabled = enable;
emit fullscreenToggled(enable);
view->switchFullscreen(enable);
}
void MachineView::showToolBar()
{
//create actions
//TODO: make actions shared between everyplace
QAction *fullscreenAction = new QAction(QIcon(":/images/oxygen/fullscreen.png"), tr("Fullscreen"), this);
fullscreenAction->setToolTip(tr("Exit Fullscreen Mode"));
fullscreenAction->setCheckable(true);
fullscreenAction->setChecked(true);
connect(fullscreenAction, SIGNAL(toggled( bool )), this, SLOT(fullscreen(bool)));
scaleAction = new QAction(QIcon(":/images/oxygen/scale.png"), tr("Scale Display"), this);
config->registerObject(scaleAction, "scaleEmbeddedDisplay");
//add a toolbar
toolBar = new FloatingToolBar(fullscreenWindow, fullscreenWindow);
toolBar->winId();
toolBar->setSide(FloatingToolBar::Top);
toolBar->addAction(fullscreenAction);
toolBar->addAction(scaleAction);
QLabel *guestLabel = new QLabel(property("name").toString(), toolBar);
toolBar->addWidget(guestLabel);
toolBar->showAndAnimate();
}
void MachineView::captureAllKeys(bool enabled)
{
view->setGrabAllKeys(enabled);
}
void MachineView::sendKey(QKeyEvent * event)
{
view->keyEvent(event);
}
void MachineView::newViewSize()
{
MachineScrollArea *currentScrollArea;
if(fullscreenEnabled)
currentScrollArea = fullscreenScrollArea;
else
currentScrollArea = embeddedScrollArea;
currentScrollArea->setProperty("scaleEmbeddedDisplay", property("scaleEmbeddedDisplay"));
currentScrollArea->resizeView(currentScrollArea->maximumViewportSize().width(), currentScrollArea->maximumViewportSize().height());
}
bool MachineView::event(QEvent * event)
{
if(event->type() == QEvent::DynamicPropertyChange)
{
//any property changes dealt with in here
QDynamicPropertyChangeEvent *propEvent = static_cast<QDynamicPropertyChangeEvent *>(event);
if(propEvent->propertyName() == "scaleEmbeddedDisplay")
{
newViewSize();
}
else if(propEvent->propertyName() == "preview")
{
splash->setPreview(property("preview").toString());
}
return false;
}
else if(event->type() == QEvent::Enter&&!embeddedScrollArea->isSplashShown())
{
view->setFocus();
view->grabKeyboard();
//repainting here fixes an issue where the vncview goes blank on mouseout
//view->repaint();
return true;
}
else if (event->type() == QEvent::Leave)
{
view->clearFocus();
view->releaseKeyboard();
//repainting here fixes an issue where the vncview goes blank on mouseout
//view->repaint();
return true;
}
else if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Return && ke->modifiers() == Qt::ControlModifier + Qt::AltModifier) {
fullscreen(false);
return true;
}
}
return QWidget::event(event);
}
| 7,967
|
C++
|
.cpp
| 220
| 30.604545
| 135
| 0.674655
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,078
|
machinewizard.cpp
|
uwolfer_qtemu/machinewizard.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machinewizard.h"
#include "config.h"
#include <QProcess>
#include <QMessageBox>
#include <QFile>
#include <QDoubleSpinBox>
#include <QBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QDir>
#include <QIcon>
#include <QComboBox>
#include <QTextStream>
#include <QSettings>
#include <QPushButton>
#include <QFileDialog>
#include <QDomElement>
#include <QCheckBox>
MachineWizard::MachineWizard(const QString &myMachinesPathParent, QWidget *parent)
: QWizard(parent)
, myMachinesPath(myMachinesPathParent)
{
addPage(new ChooseSystemPage(this));
addPage(new LocationPage(this));
addPage(new ImagePage(this));
setWindowTitle(tr("Create a new Machine"));
QSettings settings("QtEmu", "QtEmu");
QString iconTheme = settings.value("iconTheme", "oxygen").toString();
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/" + iconTheme + "/qtemu.png"));
}
QString MachineWizard::newMachine(const QString &myMachinesPath, QWidget *parent)
{
MachineWizard wizard(myMachinesPath, parent);
QString result;
bool accepted = (wizard.exec() == QDialog::Accepted);
if (accepted)
result = wizard.field("path").toString()+'/'+wizard.field("name").toString().replace(' ', '_')+".qte";
return result;
}
void MachineWizard::accept()
{
QString osName = field("name").toString();
QString osPath = field("path").toString();
QString osType = field("operatingSystem").toString();
QDir *dir = new QDir();
dir->mkpath(osPath);
QDomDocument domDocument("qtemu");
QDomProcessingInstruction process = domDocument.createProcessingInstruction(
"xml", "version=\"1.0\" encoding=\"UTF-8\"");
domDocument.appendChild(process);
QDomElement root = domDocument.createElement("qtemu");
root.setAttribute("version", "1.0");
domDocument.appendChild(root);
QDomElement machine = domDocument.createElement("machine");
root.appendChild(machine);
QDomElement domElement;
QDomText domText;
domElement = domDocument.createElement("name");
machine.appendChild(domElement);
domText = domDocument.createTextNode(osName);
domElement.appendChild(domText);
domElement = domDocument.createElement("operatingSystem");
machine.appendChild(domElement);
domText = domDocument.createTextNode(osType);
domElement.appendChild(domText);
domElement = domDocument.createElement("hdd");
machine.appendChild(domElement);
if(field("format").toInt()==0)
domText = domDocument.createTextNode(osPath+'/'+osName.replace(' ', '_')+".qcow");
else if(field("format").toInt()==1)
domText = domDocument.createTextNode(osPath+'/'+osName.replace(' ', '_')+".img");
else
domText = domDocument.createTextNode(osPath+'/'+osName.replace(' ', '_')+".vmdk");
domElement.appendChild(domText);
domElement = domDocument.createElement("memory");
machine.appendChild(domElement);
domText = domDocument.createTextNode("128");
domElement.appendChild(domText);
domElement = domDocument.createElement("notes");
machine.appendChild(domElement);
domText = domDocument.createTextNode(tr("Click here to write down some notes "
"about this machine."));
domElement.appendChild(domText);
domElement = domDocument.createElement("snapshot");
machine.appendChild(domElement);
#ifdef DEVELOPER
domText = domDocument.createTextNode("true");
#else
domText = domDocument.createTextNode("false");
#endif
domElement.appendChild(domText);
QDomElement netElement = domDocument.createElement("net-guest");
QDomElement element = domDocument.createElement("guest0");
netElement.appendChild(element);
root.appendChild(netElement);
domElement = domDocument.createElement("name");
element.appendChild(domElement);
domText = domDocument.createTextNode("Interface 0");
domElement.appendChild(domText);
domElement = domDocument.createElement("nic");
element.appendChild(domElement);
domText = domDocument.createTextNode("rtl8139");
domElement.appendChild(domText);
domElement = domDocument.createElement("nic");
element.appendChild(domElement);
domText = domDocument.createTextNode("rtl8139");
domElement.appendChild(domText);
domElement = domDocument.createElement("randomize");
element.appendChild(domElement);
domText = domDocument.createTextNode("false");
domElement.appendChild(domText);
domElement = domDocument.createElement("host");
element.appendChild(domElement);
domText = domDocument.createTextNode("Interface 0");
domElement.appendChild(domText);
domElement = domDocument.createElement("enabled");
element.appendChild(domElement);
domText = domDocument.createTextNode("true");
domElement.appendChild(domText);
domElement = domDocument.createElement("mac");
element.appendChild(domElement);
QString mac="52:54:00:";
for (int i=1;i<=6;i++)
{
mac.append(QString().setNum(qrand() % 16, 16));
if(i%2 == 0 && i != 6)
mac.append(":");
}
domText = domDocument.createTextNode(mac);
domElement.appendChild(domText);
netElement = domDocument.createElement("net-host");
element = domDocument.createElement("host0");
netElement.appendChild(element);
root.appendChild(netElement);
domElement = domDocument.createElement("name");
element.appendChild(domElement);
domText = domDocument.createTextNode("Interface 0");
domElement.appendChild(domText);
domElement = domDocument.createElement("type");
element.appendChild(domElement);
domText = domDocument.createTextNode("User Mode");
domElement.appendChild(domText);
domElement = domDocument.createElement("hostname");
element.appendChild(domElement);
domText = domDocument.createTextNode(osName);
domElement.appendChild(domText);
QFile file(osPath+'/'+osName.replace(' ', '_')+".qte");
if (!file.open(QFile::WriteOnly | QFile::Truncate))
{
QMessageBox::critical(this, tr("Error"), tr("Image NOT created!"));
return;
}
QTextStream out(&file);
domDocument.save(out, 4);
QProcess *imageCreateProcess = new QProcess(this);
imageCreateProcess->setWorkingDirectory(osPath);
QStringList arguments;
if(field("format").toInt()==0)
{
arguments << "create" << "-f" << "qcow2"
<< osName.replace(' ', '_')+".qcow";
}
else if(field("format").toInt()==1)
{
arguments << "create" << "-f" << "raw"
<< osName.replace(' ', '_')+".img";
}
else
{
arguments << "create" << "-f" << "vmdk"
<< osName.replace(' ', '_')+".vmdk";
}
arguments << QString::number(field("size").toDouble()*1024)+'M';
#ifndef Q_OS_WIN32
imageCreateProcess->start("qemu-img", arguments);
imageCreateProcess->waitForFinished();
if(imageCreateProcess->error() != QProcess::UnknownError)
{
//we may be on a system that uses "kvm-img" instead
imageCreateProcess->start("kvm-img", arguments);
imageCreateProcess->waitForFinished();
}
#elif defined(Q_OS_WIN32)
imageCreateProcess->start("qemu/qemu-img.exe", arguments);
#endif
if(imageCreateProcess->error() == QProcess::UnknownError)
QMessageBox::information(this, tr("Finished"), tr("Image created"));
else
#ifndef Q_OS_WIN32
QMessageBox::warning(this, tr("Finished"), tr("Image NOT created!<br> You may be missing either qemu-img or kvm-img, or they are not executable!"));
#elif defined(Q_OS_WIN32)
QMessageBox::warning(this, tr("Finished"), tr("Image NOT created!<br> You may be missing qemu/qemu-img.exe!"));
#endif
QDialog::accept();
}
ChooseSystemPage::ChooseSystemPage(MachineWizard *wizard)
: QWizardPage(wizard)
{
comboSystem = new QComboBox;
registerField("system", comboSystem, "currentText");
comboSystem->addItem(tr("Select a System..."));
comboSystem->addItem(tr("Linux"));
comboSystem->addItem(tr("Windows 98"));
comboSystem->addItem(tr("Windows 2000"));
comboSystem->addItem(tr("Windows XP"));
comboSystem->addItem(tr("Windows Vista"));
comboSystem->addItem(tr("ReactOS"));
comboSystem->addItem(tr("BSD"));
comboSystem->addItem(tr("Other"));
registerField("operatingSystem", comboSystem, "currentText");
connect(comboSystem, SIGNAL(activated(int)), this, SIGNAL(completeChanged()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(comboSystem);
layout->addStretch();
setLayout(layout);
setTitle(tr("Select the operating system you want to install"));
}
bool ChooseSystemPage::isComplete() const
{
return !(comboSystem->currentText()==tr("Select a System..."));
}
LocationPage::LocationPage(MachineWizard *wizard)
: QWizardPage(wizard)
{
QLineEdit *pathHidden = new QLineEdit(wizard->myMachinesPath, this);
pathHidden->setVisible(false);
registerField("myMachinesPath", pathHidden);
QLabel *nameLabel = new QLabel(tr("&Name:"));
nameLineEdit = new QLineEdit;
registerField("name", nameLineEdit);
nameLabel->setBuddy(nameLineEdit);
connect(nameLineEdit, SIGNAL(textChanged(QString)), this, SLOT(updatePath()));
QLabel *pathLabel = new QLabel(tr("&Path:"));
pathLineEdit = new QLineEdit;
registerField("path", pathLineEdit);
pathLabel->setBuddy(pathLineEdit);
QSettings settings("QtEmu", "QtEmu");
QString iconTheme = settings.value("iconTheme", "oxygen").toString();
QPushButton *pathSelectButton = new QPushButton(QIcon(":/images/" + iconTheme + "/open.png"), QString(), this);
connect(pathSelectButton, SIGNAL(clicked()), this, SLOT(setNewPath()));
QHBoxLayout *pathLayout = new QHBoxLayout;
pathLayout->addWidget(pathLineEdit);
pathLayout->addWidget(pathSelectButton);
connect(nameLineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
QGridLayout *layout = new QGridLayout;
layout->addWidget(nameLabel, 1, 0);
layout->addWidget(nameLineEdit, 1, 1);
layout->addWidget(pathLabel, 2, 0);
layout->addLayout(pathLayout, 2, 1);
layout->setRowStretch(3, 1);
setLayout(layout);
setTitle(tr("Choose name and location for the new machine"));
}
void LocationPage::updatePath()
{
pathLineEdit->setText(field("myMachinesPath").toString()+
'/'+nameLineEdit->text().replace(' ', '_'));
}
void LocationPage::setNewPath()
{
QString newPath = QFileDialog::getExistingDirectory(this, tr("Select a folder for saving the hard disk image"),
field("myMachinesPath").toString());
if (!newPath.isEmpty())
pathLineEdit->setText(newPath);
}
void LocationPage::initializePage()
{
nameLineEdit->setText(field("system").toString());
updatePath();
}
bool LocationPage::isComplete() const
{
return !(nameLineEdit->text().isEmpty());
}
ImagePage::ImagePage(MachineWizard *wizard)
: QWizardPage(wizard)
{
QLabel *sizeLabel = new QLabel(tr("&Disk image size:"));
sizeSpinBox = new QDoubleSpinBox;
registerField("size", sizeSpinBox, "value");
sizeSpinBox->setFixedSize(sizeSpinBox->sizeHint());
sizeSpinBox->setValue(2);
sizeLabel->setBuddy(sizeSpinBox);
QLabel *sizeGbLabel = new QLabel(tr("GB"));
sizeGbLabel->setFixedSize(sizeGbLabel->sizeHint());
sizeGbLabel->setBuddy(sizeSpinBox);
connect(sizeSpinBox, SIGNAL(valueChanged(double)), this, SIGNAL(completeChanged()));
QLabel *formatLabel = new QLabel(tr("Disk image format:"));
QComboBox *formatComboBox = new QComboBox;
registerField("format", formatComboBox);
formatComboBox->addItem(tr("Native image (qcow)"));
formatComboBox->addItem(tr("Raw image (img)"));
formatComboBox->addItem(tr("VMWare image (vmdk)"));
//encryptionCheckBox = new QCheckBox;//qemu does not appear to support this very well, and kvm doesn't boot encrypted images at all...
QLabel *formatInfoLabel = new QLabel(tr("The native image format enables<br>"
"suspend/resume features, all other formats<br>"
"lack suspend/resume. Use \"Native image (qcow)\"<br>"
"unless you know what you are doing."));
formatLabel->setBuddy(formatComboBox);
connect(formatComboBox, SIGNAL(activated(int)), this, SIGNAL(completeChanged()));
QVBoxLayout *layout = new QVBoxLayout;
QHBoxLayout *sizeLayout = new QHBoxLayout;
sizeLayout->addWidget(sizeLabel);
sizeLayout->addWidget(sizeSpinBox);
sizeLayout->addWidget(sizeGbLabel);
QHBoxLayout *formatLayout = new QHBoxLayout;
formatLayout->addWidget(formatLabel);
formatLayout->addWidget(formatComboBox);
layout->addLayout(sizeLayout);
layout->addLayout(formatLayout);
layout->addStretch();
layout->addWidget(formatInfoLabel);
layout->addStretch();
setLayout(layout);
setTitle(tr("Specify disk image details"));
}
void ImagePage::cleanupPage()
{
sizeSpinBox->setValue(0);
}
bool ImagePage::isComplete() const
{
return (sizeSpinBox->value()!=0);
}
/*void ImagePage::enableEncryption(int choice)
{
if(choice == 0)
encryptionCheckBox->setEnabled(true);
else
encryptionCheckBox->setEnabled(false);
}*/
| 14,548
|
C++
|
.cpp
| 353
| 35.84136
| 156
| 0.692592
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,079
|
machineconfigobject.cpp
|
uwolfer_qtemu/machineconfigobject.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machineconfigobject.h"
#include <QObject>
#include <QStringList>
#include <QDynamicPropertyChangeEvent>
#include <QEvent>
#include <QButtonGroup>
#include <QAbstractButton>
#include <QComboBox>
MachineConfigObject::MachineConfigObject(QObject *parent, MachineConfig *config)
: QObject(parent)
, myConfig(0)
{
setConfig(config);
connect(config, SIGNAL(optionChanged(QString, QString, QString, QVariant)),this,SLOT(configChanged(QString, QString, QString, QVariant)));
}
MachineConfigObject::~MachineConfigObject()
{
}
/**
sets the config object to use (config file object)
*/
void MachineConfigObject::setConfig(MachineConfig * config)
{
if(config!=0)
myConfig = config;
else
myConfig = new MachineConfig(this);
}
/**
get an option from the config file
*/
QVariant MachineConfigObject::getOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &defaultValue)
{
return myConfig->getOption(nodeType, nodeName, optionName, defaultValue);
}
/**
get an option from the config file using the short syntax
*/
QVariant MachineConfigObject::getOption(const QString &optionName, const QVariant &defaultValue)
{
return getOption("machine", QString(), optionName, defaultValue);
}
/**
sets an option in the config file
*/
void MachineConfigObject::setOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value)
{
myConfig->setOption(nodeType, nodeName, optionName, value);
}
/**
set an option in the config file using the short syntax
*/
void MachineConfigObject::setOption(const QString &optionName, const QVariant &value)
{
setOption("machine", QString(), optionName, value);
}
/**
add an object to the list along with the config option it uses, stored in the object as a property.
*/
void MachineConfigObject::registerObject(QObject *object, const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &defaultValue)
{
object->setProperty("nodeType", nodeType);
object->setProperty("nodeName", nodeName);
if(optionName.isEmpty())
{
//dealing with an object with multiple properties
//add all properties in the config under this node name/type
QStringList options = myConfig->getAllOptionNames(nodeType, nodeName);
for(int i=0;i<options.size();i++)
{
object->setProperty(options.at(i).toAscii(), myConfig->getOption(nodeType, nodeName, options.at(i)));
}
//add event filter
object->installEventFilter(this);
}
else
{
//object with one property
object->setProperty("optionName", optionName);
//set object value
setObjectValue(object, nodeType, nodeName, optionName, defaultValue);
//connect signals/slots - based on type
}
registeredObjects.append(object);
}
/**
registers an object using the short syntax
*/
void MachineConfigObject::registerObject(QObject *object, const QString &optionName, const QVariant &defaultValue)
{
registerObject(object, "machine", QString(), optionName, defaultValue);
}
/**
unregister an object
*/
void MachineConfigObject::unregisterObject(QObject *object)
{
if(object->property("optionName") == QVariant())
{
QStringList options = myConfig->getAllOptionNames(object->property("nodeType").toString(), object->property("nodeName").toString());
for(int i=0;i<options.size();i++)
{
object->setProperty(options.at(i).toAscii(), QVariant());
}
object->removeEventFilter(this);
}
else
object->setProperty("optionName", QVariant());
object->setProperty("nodeType", QVariant());
object->setProperty("nodeName", QVariant());
registeredObjects.removeAll(object);
}
/**
set an object's property to the value of its associated config option, or default
*/
void MachineConfigObject::setObjectValue(QObject * object, const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &defaultValue)
{
//get the value from the config
QVariant value = getOption(nodeType, nodeName, optionName, defaultValue);
#ifdef DEVELOPER
//qDebug("setting object for " + optionName.toAscii() + " to " + value.toByteArray());
#endif
//disconnect so that we don't go in a loop forever
//set the object's value, analyzing its type / properties to determine how to do so.
//multiple property object
if(object->property("optionName").isNull())
{
object->removeEventFilter(this);
if(object->property(optionName.toAscii()) != value)
object->setProperty(optionName.toAscii(), value);
object->installEventFilter(this);
}
//QButtonGroup handling is tricky...
else if(object->inherits("QButtonGroup"))
{
object->disconnect(this);
QButtonGroup *group = static_cast<QButtonGroup *>(object);
QList<QAbstractButton *> buttons = group->buttons();
for(int i=0;i<buttons.size();i++)
{
if(((buttons.at(i)->property("value").toString().isEmpty()) && buttons.at(i)->text() == value.toString()) || buttons.at(i)->property("value") == value)
{
if(object->property("checked").toBool() != true)
buttons.at(i)->setProperty("checked", true);
}
else
{
if(object->property("checked").toBool() != false)
buttons.at(i)->setProperty("checked", false);
}
}
connect(object, SIGNAL(buttonClicked(QAbstractButton *)), this, SLOT(getObjectValue()));
}
else if(object->inherits("QComboBox"))
{
object->disconnect(this);
QComboBox *thisBox = static_cast<QComboBox *>(object);
int index;
if(thisBox->findData(value) == -1)
index = thisBox->findText(value.toString());
else
index = thisBox->findData(value);
if(index!=-1 && object->property("currentIndex").toInt() != index)
object->setProperty("currentIndex", index);
else if(thisBox->currentText() != value.toString() && thisBox->itemData(thisBox->currentIndex()) != value)
thisBox->setEditText(value.toString());
connect(object, SIGNAL(currentIndexChanged(int)), this, SLOT(getObjectValue()));
connect(object, SIGNAL(editTextChanged(QString)), this, SLOT(getObjectValue()));
}
else if (object->inherits("QRadioButton"))
{
object->disconnect(this);
if(object->property("value") == value && object->property("checked").toBool() != true)
object->setProperty("checked", true);
else if (object->property("value").isNull() && object->property("checked") != value)
object->setProperty("checked", value);
connect(object, SIGNAL(toggled(bool)), this, SLOT(getObjectValue()));
}
else if (object->inherits("QAbstractButton")||object->inherits("QAction"))
{
object->disconnect(this);
object->setProperty("checkable", true);
if(object->property("valueIfTrue").isNull())
{
if(object->property("checked") != value)
object->setProperty("checked", value);
}
else
{
if(object->property("valueIfTrue") != value)
object->setProperty("checked", false);
else
object->setProperty("checked", true);
}
connect(object, SIGNAL(toggled(bool)), this, SLOT(getObjectValue()));
}
else if (object->inherits("QSpinBox")||object->inherits("QAbstractSlider"))
{
object->disconnect(this);
if(object->property("value") != value)
object->setProperty("value", value);
connect(object, SIGNAL(valueChanged(int)), this, SLOT(getObjectValue()));
}
else if (object->inherits("QLineEdit"))
{
object->disconnect(this);
if(object->property("text") != value)
object->setProperty("text", value);
connect(object, SIGNAL(textChanged(QString)), this, SLOT(getObjectValue()));
}
else if (object->inherits("QTextEdit"))
{
object->disconnect(this);
if(object->property("plainText") != value)
object->setProperty("plainText", value);
connect(object, SIGNAL(textChanged()), this, SLOT(getObjectValue()));
}
else if (object->inherits("QWidget") && object->property("enableDisable").toBool() == true)
{
//if the "enableDisable" property is set to true, we want to enable or disable the widget.
QWidget *thisWidget = static_cast<QWidget *>(object);
thisWidget->setEnabled(value.toBool());
}
else
{
//if it's none of those... we don't know what it is yet.
//qDebug("unknown object type" + QByteArray(object->metaObject()->className()));
//we set a single property (the option name) to the value.
object->removeEventFilter(this);
object->setProperty(optionName.toAscii(), value);
object->installEventFilter(this);
}
//qDebug("set!");
}
/**
event handler for intercepting changes in objects with multiple properties
*/
bool MachineConfigObject::eventFilter(QObject * object, QEvent * event)
{
if (event->type() == QEvent::DynamicPropertyChange) {
QDynamicPropertyChangeEvent *myEvent = static_cast<QDynamicPropertyChangeEvent *>(event);
QString nodeType;
QString nodeName;
QString optionName;
QVariant value;
nodeType = object->property("nodeType").toString();
nodeName = object->property("nodeName").toString();
optionName = myEvent->propertyName();
value = object->property(optionName.toAscii());
//save the option to the config
setOption(nodeType, nodeName, optionName, value);
}
// allow further processing
return false;
}
/**
get the value of the calling object and sets the value of the associated config option
*/
void MachineConfigObject::getObjectValue()
{
QVariant value;
QObject *object = sender();
//get value from the object, analyzing its type / properties to determine how to do so.
if (object->inherits("QButtonGroup"))
{
QButtonGroup *group = static_cast<QButtonGroup *>(object);
if(group->checkedButton()->property("value").toString().isEmpty())
value = group->checkedButton()->text();
else
value = group->checkedButton()->property("value");
}
else if(object->inherits("QComboBox"))
{
QComboBox *thisCombo = static_cast<QComboBox *>(object);
if(!thisCombo->itemData(thisCombo->currentIndex()).isNull())
value = thisCombo->itemData(thisCombo->currentIndex());
else
value = object->property("currentText");
}
else if (object->inherits("QRadioButton"))
{
if(object->property("checked").toBool() && object->property("value").isValid())
value = object->property("value");
else if(object->property("value").isNull())
value = object->property("checked");
}
else if (object->inherits("QAbstractButton")||object->inherits("QAction"))
{
if(object->property("valueIfTrue").isNull())
value = object->property("checked");
else if(object->property("checked").toBool())
value = object->property("valueIfTrue");
else
value = object->property("valueIfFalse");
}
else if (object->inherits("QSpinBox")||object->inherits("QAbstractSlider"))
{
value = object->property("value");
}
else if (object->inherits("QLineEdit"))
{
value = object->property("text");
}
else if (object->inherits("QTextEdit"))
{
value = object->property("plainText");
}
else
{
//if it's none of those... we don't know what it is yet.
qDebug("unknown object type" + QByteArray(object->metaObject()->className()));
}
//save the option to the config
if(value.isValid())
{
setOption(object->property("nodeType").toString(), object->property("nodeName").toString(), object->property("optionName").toString(), value);
}
}
/**
slot is activated if there is a config change
*/
void MachineConfigObject::configChanged(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value)
{
QObject *object;
for(int i=0;i<registeredObjects.size();i++)
{
object = registeredObjects.at(i);
QString thisNodeType = object->property("nodeType").toString();
QString thisNodeName = object->property("nodeName").toString();
QString thisOptionName = object->property("optionName").toString();
if(( thisNodeType == nodeType ) && ( thisNodeName == nodeName || thisNodeName.isEmpty() ) && ( thisOptionName.isEmpty() || thisOptionName == optionName ))
{
setObjectValue(object, nodeType, nodeName, optionName, value);
}
}
}
/**
gets the config object used (config file object)
*/
MachineConfig * MachineConfigObject::getConfig()
{
return myConfig;
}
| 14,277
|
C++
|
.cpp
| 365
| 33.071233
| 165
| 0.656126
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,080
|
interfacemodel.cpp
|
uwolfer_qtemu/interfacemodel.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
/****************************************************************************
**
** C++ Implementation: interfacemodel
**
** Description: provides a model for the model/view framework to describe the
** various options for a qemu network interface, both guest and host models
** are provided.
**
****************************************************************************/
#include <QStringList>
#include "interfacemodel.h"
#include "machineconfigobject.h"
InterfaceModel::InterfaceModel(MachineConfigObject * config, QString nodeType, QObject * parent)
: QAbstractTableModel(parent)
, config(config)
, nodeType(nodeType)
{
connect(config->getConfig(), SIGNAL(optionChanged(const QString&, const QString&, const QString&, const QVariant&)), this, SLOT(optionChanged(const QString&, const QString&, const QString&, const QVariant&)));
}
int InterfaceModel::rowCount(const QModelIndex & parent) const
{
if(parent.isValid())
return 0;
int rows = config->getConfig()->getNumOptions(nodeType, "");
//qDebug("rows %i", rows);
return rows;
}
int InterfaceModel::columnCount(const QModelIndex & parent) const
{
if(parent.isValid())
return 0;
return columns.size();
}
QVariant InterfaceModel::data(const QModelIndex & index, int role) const
{
if(!index.isValid())
return QVariant();
//maybe this could be optimized by caching the stringlists...
QString nodeName = rowName(index.row());
QString optionName = colName(index.column());
if (role == Qt::DisplayRole || role == Qt::EditRole)
return config->getOption(nodeType, nodeName, optionName, QVariant());
else
return QVariant();
}
QVariant InterfaceModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if (role == Qt::DisplayRole)
return columns.at(section);
}
return QAbstractTableModel::headerData(section, orientation, role);
}
Qt::ItemFlags InterfaceModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool InterfaceModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if (index.isValid() && (role == Qt::EditRole || role == Qt::DisplayRole))
{
QString nodeName = rowName(index.row());
QString optionName = colName(index.column());
config->getConfig()->setOption(nodeType, nodeName, optionName, value);
emit dataChanged(index, index);
return true;
}
return false;
}
QString InterfaceModel::rowName(int row) const
{
QStringList names = config->getConfig()->getAllOptionNames(nodeType, "");
if(row <= names.size())
return names.at(row);
else
return QString();
}
QString InterfaceModel::colName(int col) const
{
return(columns.at(col));
}
void InterfaceModel::optionChanged(const QString & nodeType, const QString & nodeName, const QString & optionName, const QVariant & value)
{
if(nodeType == this->nodeType)
{
reset();
}
}
GuestInterfaceModel::GuestInterfaceModel(MachineConfigObject * config, QObject * parent)
: InterfaceModel(config, QString("net-guest"), parent)
{
columns << "name" << "mac" << "enabled";
}
bool GuestInterfaceModel::insertRows(int row, int count, const QModelIndex & parent)
{
Q_UNUSED(parent);
QString nodeName;
int interfaceNumber = 0;
beginInsertRows(parent, row, row + count - 1);
for (int i=0; i<count; i++)
{
for(;config->getOption(nodeType, "", QString("guest" + QString::number(interfaceNumber)), QVariant()).isValid();interfaceNumber++);
nodeName = "guest" + QString::number(interfaceNumber);
//set all options
config->setOption(nodeType, nodeName, "name", QString(QString("Interface ") + QString::number(interfaceNumber)));
config->setOption(nodeType, nodeName, "nic", "rtl8139");
config->setOption(nodeType, nodeName, "mac", "random");
config->setOption(nodeType, nodeName, "randomize", false);
config->setOption(nodeType, nodeName, "host", QString(QString("Interface ") + QString::number(interfaceNumber)));
config->setOption(nodeType, nodeName, "enabled", true);
}
endInsertRows();
return true;
}
bool GuestInterfaceModel::removeRows(int row, int count, const QModelIndex & parent)
{
Q_UNUSED(parent);
QString nodeName;
beginRemoveRows(parent, row, row + count - 1);
for (int i = row; i < (row + count); i++)
{
nodeName = config->getConfig()->getAllOptionNames(nodeType, "").at(i);
config->getConfig()->clearOption(nodeType, "", nodeName);
}
endRemoveRows();
return true;
}
HostInterfaceModel::HostInterfaceModel(MachineConfigObject * config, QObject * parent)
: InterfaceModel(config, QString("net-host"), parent)
{
columns << "name" << "type";
}
bool HostInterfaceModel::insertRows(int row, int count, const QModelIndex & parent)
{
Q_UNUSED(parent);
QString nodeName;
int interfaceNumber = 0;
beginInsertRows(parent, row, count);
for (int i=0; i<count; i++)
{
for(;config->getOption(nodeType, "", QString("host" + QString::number(interfaceNumber)), QVariant()).isValid();interfaceNumber++);
nodeName = "host" + QString::number(interfaceNumber);
//set all options
config->setOption(nodeType, nodeName, "name", QString(QString("Interface ") + QString::number(interfaceNumber)));
config->setOption(nodeType, nodeName, "type", "User Mode");
config->setOption(nodeType, nodeName, "interface", "qtemu-" + config->getOption("name").toString().replace(' ', '_') + '-' + config->getOption(nodeType, nodeName, "name", "Interface_" + QString::number(interfaceNumber)).toString().replace(' ', '_'));
config->setOption(nodeType, nodeName, "bridgeInterface", "qtemu-" + config->getOption("name").toString().replace(' ', '_') + "-br" + QString::number(interfaceNumber));
config->setOption(nodeType, nodeName, "hardwareInterface", "eth0");
config->setOption(nodeType, nodeName, "spanningTree", false);
config->setOption(nodeType, nodeName, "ifUp", QString());
config->setOption(nodeType, nodeName, "ifDown", QString());
config->setOption(nodeType, nodeName, "hostname", "qtemu_guest");
config->setOption(nodeType, nodeName, "tftp", false);
config->setOption(nodeType, nodeName, "tftpPath", QString());
config->setOption(nodeType, nodeName, "bootp", false);
config->setOption(nodeType, nodeName, "bootpPath", QString());
config->setOption(nodeType, nodeName, "vlanType", "udp");
config->setOption(nodeType, nodeName, "address", "127.0.0.1");
config->setOption(nodeType, nodeName, "port", "9000");
}
endInsertRows();
return true;
}
bool HostInterfaceModel::removeRows(int row, int count, const QModelIndex & parent)
{
Q_UNUSED(parent);
QString nodeName;
beginRemoveRows(parent, row, row + count - 1);
for (int i = row; i < (row + count); i++)
{
nodeName = config->getConfig()->getAllOptionNames(nodeType, "").at(i);
config->getConfig()->clearOption(nodeType, "", nodeName);
}
endRemoveRows();
return true;
}
| 8,358
|
C++
|
.cpp
| 201
| 37.124378
| 258
| 0.664123
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,081
|
netconfig.cpp
|
uwolfer_qtemu/netconfig.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machineconfigobject.h"
#include "netconfig.h"
#include <QByteArray>
#include <QDebug>
#include <stdlib.h>
#include <QTime>
//Main NetConfig Class
NetConfig::NetConfig(QObject *parent, MachineConfigObject *config)
: QObject(parent)
, config(config)
{
hostIfs = new QList<HostInterface*>;
guestIfs = new QList<GuestInterface*>;
hostIfNames = QStringList();
}
void NetConfig::buildIfs()
{
hostIfs->clear();
guestIfs->clear();
QStringList guestNames = config->getConfig()->getAllOptionNames("net-guest", "");
QStringList hostNames = config->getConfig()->getAllOptionNames("net-host", "");
for(int i=0;i<hostNames.size();i++)
{
hostIfs->append(new HostInterface(this,hostNames.at(i)));
hostIfs->last()->setVlan(i);
hostIfNames << hostIfs->last()->property("name").toString();
}
for(int i=0;i<guestNames.size();i++)
{
guestIfs->append(new GuestInterface(this,guestNames.at(i)));
if(guestIfs->last()->property("host").isValid())
{
guestIfs->last()->setVlan(hostIfs->at(hostIfNames.indexOf(guestIfs->last()->property("host").toString()))->getVlan());
}
else
{
guestIfs->last()->setVlan(-1);
guestIfs->last()->setProperty("enabled", false);
}
}
}
QStringList NetConfig::getOptionString()
{
buildIfs();
QStringList opts;
QList<NetInterface*> usedHostIfs;
for(int i=0;i<guestIfs->size();i++)
{
if(guestIfs->at(i)->property("enabled").toBool())
{
opts << guestIfs->at(i)->parseOpts();
usedHostIfs.append(hostIfs->at(hostIfNames.indexOf(guestIfs->at(i)->property("host").toString())));
}
}
for(int i=0;i<usedHostIfs.size();i++)
{
opts << usedHostIfs.at(i)->parseOpts();
}
return opts;
}
//Basic NetInterface Class
NetInterface::NetInterface(NetConfig *parent, QString nodeType, QString nodeName)
: QObject(parent)
, config(parent->config)
, nodeType(nodeType)
, nodeName(nodeName)
{
config->registerObject(this, nodeType, nodeName);
}
int NetInterface::getVlan()
{
return vlan;
}
void NetInterface::setVlan(int number)
{
vlan = number;
}
QStringList NetInterface::parseOpts()
{
return QStringList();
}
GuestInterface::GuestInterface(NetConfig *parent, QString nodeName)
: NetInterface(parent, QString("net-guest"), nodeName)
{
}
QStringList GuestInterface::parseOpts()
{
static bool firstTime = true;
//need to come up with the mac properly.
QString mac;
if (property("randomize").toBool() || property("mac").toString() == tr("random"))
{
if (firstTime)
{
firstTime = false;
QTime midnight(0, 0, 0);
qsrand(midnight.secsTo(QTime::currentTime()));
}
mac="52:54:00:";
for (int i=1;i<=6;i++)
{
mac.append(QString().setNum(qrand() % 16, 16));
if(i%2 == 0 && i != 6)
mac.append(":");
}
setProperty("mac", mac);
}
else
{
mac = property("mac").toString();
}
QStringList opts;
opts << "-net" << "nic,vlan=" + QString().setNum(vlan) + ",macaddr=" + mac + ",model=" + property("nic").toString();
return opts;
}
HostInterface::HostInterface(NetConfig *parent, QString nodeName)
: NetInterface(parent, QString("net-host"), nodeName)
{
}
QStringList HostInterface::parseOpts()
{
QString type;
QStringList netOpts;
QStringList opts;
//FIXME: this will not work for a translated gui??
if(property("type").toString() == tr("User Mode"))
{
//-net user[,vlan=n][,hostname=name]
type="user";
//additional options for this type:
netOpts << "hostname=" + property("hostname").toString();
//tftp and bootp
if(property("bootp").toBool())
opts << "-bootp" << property("bootpPath").toString();
if(property("tftp").toBool())
opts << "-tftp" << property("tftpPath").toString();
//TODO: add SMB support
}
else if(property("type").toString() == tr("Bridged Interface"))
{
//-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]
type="tap";
//additional options for this type:
//[fd=h]
netOpts << "ifname=" + property("interface").toString();
//[script=file]
netOpts << "script=no";
netOpts << "downscript=no";
}
else if(property("type").toString() == tr("Routed Interface"))
{
//-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]
type="tap";
//additional options for this type:
//[fd=h]
netOpts << "ifname=" + property("interface").toString();
//[script=file]
netOpts << "script=no";
netOpts << "downscript=no";
}
else if(property("type").toString() == tr("Shared Virtual Lan"))
{
type="socket";
if(property("vlanType").toString() == "udp")
{
//-net socket[,vlan=n][,fd=h][,mcast=maddr:port]
netOpts << "mcast=" + property("address").toString() + ':' + property("port").toString();
}
else
{
//-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]
qDebug() << "tcp not yet supported";
}
}
else if(property("type").toString() == tr("Custom TAP"))
{
//-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]
type="tap";
netOpts << "ifname=" + property("interface").toString();
netOpts << "script=" + property("ifUp").toString();
netOpts << "downscript=" + property("ifDown").toString();
}
opts << "-net" << type + ",vlan=" + QString().setNum(vlan) + (netOpts.isEmpty()?QString():(',' + netOpts.join(",")));
return opts;
}
HostActionItem::HostActionItem(NetConfig *parent, HostAction action, HostItem item, QString interface, QString interfaceTo)
:QObject(parent)
,action(action)
,item(item)
,interface(interface)
,toInterface(interfaceTo)
{
}
| 7,163
|
C++
|
.cpp
| 215
| 27.530233
| 130
| 0.606388
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,082
|
harddiskmanager.cpp
|
uwolfer_qtemu/harddiskmanager.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "harddiskmanager.h"
#include "machineprocess.h"
#include "qtemuenvironment.h"
#include <QTimer>
#include <QFileInfo>
#include <QProcess>
HardDiskManager::HardDiskManager(MachineProcess *parent)
: QObject(parent)
, parent(parent)
{
}
HardDiskManager::~HardDiskManager()
{
}
void HardDiskManager::upgradeImage()
{
emit processingImage(true);
upgradeImageName = currentImage.path() + '/' + currentImage.completeBaseName() + ".qcow";
#ifndef Q_OS_WIN32
QString program = "qemu-img";
#elif defined(Q_OS_WIN32)
QString program = "qemu/qemu-img.exe";
#endif
QStringList arguments;
currentProcess = new QProcess(this);
connect(currentProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(upgradeComplete(int)));
arguments << "convert" << currentImage.filePath() << "-O" << "qcow2" << upgradeImageName;
currentProcess->start(program, arguments);
updateProgressTimer = new QTimer(this);
connect(updateProgressTimer, SIGNAL(timeout()), this, SLOT(updateUpgradeProgress()));
updateProgressTimer->start(1000);
}
void HardDiskManager::upgradeComplete(int status)
{
emit processingImage(false);
if(status == 0)
{
setProperty("hdd", QVariant(upgradeImageName));
}
else
{
emit error(tr("Upgrading your hard disk image failed! Do you have enough disk space?<br />You may want to try upgrading manually using the program qemu-img."));
}
}
void HardDiskManager::updateUpgradeProgress()
{
// qint64 size = QFileInfo(upgradeImageName).size();
//TODO: update a progress bar
}
void HardDiskManager::testImage()
{
if(!currentImage.exists()||!currentImage.isFile())
{
emit imageFormat("none");
emit imageUpgradable(false);
emit supportsSuspending(false);
emit supportsResuming(false);
emit imageSize(0);
emit phySize(0);
return;
}
#ifndef Q_OS_WIN32
QString program = "qemu-img";
#elif defined(Q_OS_WIN32)
QString program = "qemu/qemu-img.exe";
#endif
QStringList arguments;
QProcess *testProcess = new QProcess(this);
arguments << "info" << currentImage.filePath();
testProcess->start(program, arguments);
testProcess->waitForFinished();
#ifndef Q_OS_WIN32
if(testProcess->error() != QProcess::UnknownError)
{
//we may be on a system that uses "kvm-img" instead
program = "kvm-img";
testProcess->start(program, arguments);
testProcess->waitForFinished();
}
#endif
//make sure we didn't error out
if(testProcess->error() != QProcess::UnknownError)
{
emit imageFormat("unknown");
emit imageUpgradable(false);
emit supportsSuspending(false);
emit supportsResuming(false);
emit imageSize(0);
emit phySize(0);
#ifndef Q_OS_WIN32
emit error(tr("QtEmu could not run the kvm-img or qemu-img programs in your path. Disk image statistics will be unavailable."));
#elif defined(Q_OS_WIN32)
emit error(tr("QtEmu could not run the qemu/qemu-img.exe program. Disk image statistics will be unavailable."));
#endif
return;
}
//time to parse the output and get all the info available
//splits are on colons.
QStringList output = QString(testProcess->readAll()).split('\n');
currentFormat = output.at(1).split(':').at(1).simplified();
emit imageFormat(currentFormat);
if(currentFormat!="qcow2")
{
emit imageUpgradable(true);
suspendable = false;
}
else
{
emit imageUpgradable(false);
suspendable = true;
}
if(property("snapshot").toBool())
suspendable = false;
emit supportsSuspending(suspendable);
QString virtSize = output.at(2).section('(', 1);
virtSize.chop(6);
virtSize.simplified();
virtualSize = virtSize.toLongLong();
emit imageSize(virtualSize);
emit phySize(currentImage.size());
resumable = false;
if(output.size()>6)
{
QString currentLine;
QStringList list;
for(int i = 7; i<output.size() - 1;i++)
{
currentLine = output.at(i);
list = currentLine.split(QRegExp("\\W+"));
if(currentLine.split(QRegExp("\\W+")).at(1) == "Default")
{
resumable = true;
}
}
}
if(property("snapshot").toBool())
resumable = false;
emit supportsResuming(resumable);
}
bool HardDiskManager::event(QEvent * event)
{
if(event->type() == QEvent::DynamicPropertyChange)
{
//any property changes dealt with in here
QDynamicPropertyChangeEvent *propEvent = static_cast<QDynamicPropertyChangeEvent *>(event);
if((propEvent->propertyName() == "hdd" || propEvent->propertyName() == "snapshot") && parent->state()==MachineProcess::NotRunning)
{
currentImage = QFileInfo(property("hdd").toString());
testImage();
}
return false;
}
return QObject::event(event);
}
bool HardDiskManager::isSuspendable() const
{
return suspendable;
}
| 6,114
|
C++
|
.cpp
| 180
| 29.005556
| 168
| 0.661086
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,083
|
usbconfig.cpp
|
uwolfer_qtemu/usbconfig.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "usbconfig.h"
#include "machineconfigobject.h"
#include "machineprocess.h"
#include "machinetab.h"
UsbConfig::UsbConfig(MachineProcess * parent, MachineConfigObject * config)
: QObject(parent)
, config(config)
, parent(parent)
{
config->registerObject(this);
qobject_cast<MachineTab *>(parent->parent());
}
QStringList UsbConfig::getOptionString()
{
QStringList hostDeviceNames = config->getConfig()->getAllOptionNames("usb", "");
QStringList optionString;
foreach(QString name, hostDeviceNames)
{
optionString << "-usbdevice" << "host:" + config->getOption("usb", name, "address", QString()).toString();
}
return optionString;
}
void UsbConfig::vmAddDevice(QString id)
{
if(parent->state() == 2)
{
parent->write(QString("usb_add host:" + id + '\n').toAscii());
}
}
void UsbConfig::vmRemoveDevice(QString id)
{ if(parent->state() == 2)
{
parent->write(QString("usb_del host:" + id + '\n').toAscii());
}
//this may not be right... or needed sometimes.
//if the device is physically removed this is exteranious,
//if you just uncheck the device's checkbox, then it is required.
}
| 2,222
|
C++
|
.cpp
| 60
| 34.05
| 114
| 0.658469
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,085
|
guesttoolslistener.cpp
|
uwolfer_qtemu/guesttoolslistener.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "guesttoolslistener.h"
#include "GuestTools/modules/clipboard/clipboardsync.h"
#include <QLocalSocket>
#include <QDataStream>
#include <QVariant>
//
GuestToolsListener::GuestToolsListener( QString location, QObject *parent )
: QObject(parent)
{
blockSize = 0;
toolSocket = new QLocalSocket(this);
//connect(toolSocket, SIGNAL(connected()), this, SLOT(setupConnection()));
//server = new QLocalServer(this);
toolSocket->connectToServer(location, QIODevice::ReadWrite);
qDebug() << "connecting to" << location;
setupConnection();
}
void GuestToolsListener::setupConnection()
{
qDebug() << "setting up guest tools";
addModules();
connect(toolSocket, SIGNAL(readyRead()), this, SLOT(receiveData()));
}
void GuestToolsListener::receiveData()
{
//connect the stream
QDataStream stream(toolSocket);
stream.setVersion(QDataStream::Qt_4_0);
//get the size of the data chunk
if (blockSize == 0) {
if (toolSocket->bytesAvailable() < (int)sizeof(quint64))
return;
stream >> blockSize;
}
//don't continue until we have all the data
if ((quint64)(toolSocket->bytesAvailable()) < blockSize)
return;
QString usesModule;
QVariant data;
stream >> usesModule >> data;
blockSize = 0;
for(int i = 0; i < modules.size(); i++)
{
if(modules.at(i)->moduleName() == usesModule)
{
qDebug() << "received data from"<< usesModule;
modules.at(i)->receiveData(data);
return;
}
}
qDebug() << "invalid module" << usesModule;
}
void GuestToolsListener::addModules()
{
modules.append(new ClipboardSync(this));
}
void GuestToolsListener::dataSender(QString module, QVariant &data)
{
//so that we don't try to send more than one at a time
//sender()->blockSignals(true);
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint64)0;
out << module;
out << data;
out.device()->seek(0);
out << (quint64)(block.size() - sizeof(quint64));
toolSocket->write(block);
//re-allow signals
//sender()->blockSignals(false);
}
//
| 3,229
|
C++
|
.cpp
| 95
| 30.178947
| 78
| 0.659499
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,086
|
machineconfig.cpp
|
uwolfer_qtemu/machineconfig.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machineconfig.h"
#include <QFile>
#include <QVariant>
#include <QDomDocument>
#include <QDomElement>
#include <QDomText>
#include <QString>
#include <QTextStream>
#include <QStringList>
MachineConfig::MachineConfig(QObject *parent, const QString &config)
: QObject(parent)
{
if(!config.isEmpty())
loadConfig(config);
}
MachineConfig::~MachineConfig()
{
saveConfig(configFile->fileName());
configFile->deleteLater();
}
bool MachineConfig::loadConfig(const QString &fileName)
{
configFile = new QFile(fileName);
if (!configFile->open(QFile::ReadOnly | QFile::Text))
{
qDebug("Cannot read file" + fileName.toAscii() + ", " + configFile->errorString().toAscii());
domDocument.appendChild(domDocument.createElement("qtemu"));
root = domDocument.documentElement();
return false;
}
QString errorStr;
int errorLine;
int errorColumn;
if (!domDocument.setContent(configFile, true, &errorStr, &errorLine, &errorColumn))
{
qDebug("Parse error at line %1, column %2:\n" + errorStr.toAscii(), errorLine, errorColumn);
return false;
}
root = domDocument.documentElement();
if (root.tagName() != "qtemu")
{
qDebug("The file is not a QtEmu file.");
return false;
}
else if (root.hasAttribute("version") && root.attribute("version") != "1.0")
{
qDebug("The file is not a QtEmu version 1.0 file.");
return false;
}
return true;
}
bool MachineConfig::saveConfig(const QString &fileName) const
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text))
{
qDebug("Cannot write file " + fileName.toAscii() +":\n" + file.errorString().toAscii());
return false;
}
QTextStream out(&file);
domDocument.save(out, 4);
return true;
}
void MachineConfig::setOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value)
{
//save the value to the config
QDomElement child = root.firstChildElement(nodeType);
QDomElement subChild;
if(child.isNull())
{
//make a new node
child = domDocument.createElement(nodeType);
root.appendChild(child);
subChild = child;
}
else
{
//existing node
subChild = child;
}
//find the sub child (nodeName)
if(!nodeName.isEmpty())
{
subChild = child.firstChildElement(nodeName);
if(subChild.isNull())
{
subChild = domDocument.createElement(nodeName);
child.appendChild(subChild);
}
}
QDomElement oldElement = subChild.firstChildElement(optionName);
if (oldElement.isNull())
{
oldElement = domDocument.createElement(optionName);
subChild.appendChild(oldElement);
}
QDomElement newElement = domDocument.createElement(optionName);
QDomText newText = domDocument.createTextNode(value.toString());
newElement.appendChild(newText);
subChild.replaceChild(newElement, oldElement);
//save the document
saveConfig(configFile->fileName());
emit optionChanged(nodeType, nodeName, optionName, value);
}
QVariant MachineConfig::getOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant defaultValue)
{
//return the value of node named nodeType's child with property name=nodeName's child named optionName
QDomElement typeElement;
QDomElement nameElement;
QDomElement optionElement;
QVariant optionValue = defaultValue;
typeElement = root.firstChildElement(nodeType);
nameElement = typeElement;
if(!nodeName.isEmpty())
{
nameElement = typeElement.firstChildElement(nodeName);
}
optionElement = nameElement.firstChildElement(optionName);
if(optionElement.isNull())
{
//the option did not exist: set default value!
setOption(nodeType, nodeName, optionName, defaultValue);
optionValue = defaultValue;
}
else
optionValue = QVariant(optionElement.text());
return optionValue;
}
QStringList MachineConfig::getAllOptionNames(const QString &nodeType, const QString &nodeName) const
{
QDomElement typeElement;
QDomElement nameElement;
QDomElement optionElement;
QStringList optionNameList;
if(nodeName.isEmpty())
{
nameElement = root.firstChildElement(nodeType);
}
else
{
typeElement = root.firstChildElement(nodeType);
if(nodeName == "*")
nameElement = typeElement.firstChildElement();
else
nameElement = typeElement.firstChildElement(nodeName);
}
optionElement = nameElement.firstChildElement();
while(!optionElement.isNull())
{
optionNameList.append(optionElement.nodeName());
optionElement = optionElement.nextSiblingElement();
}
return optionNameList;
}
void MachineConfig::clearOption(const QString & nodeType, const QString & nodeName, const QString & optionName)
{
QDomElement typeElement;
QDomElement nameElement;
QDomElement optionElement;
typeElement = root.firstChildElement(nodeType);
nameElement = typeElement;
if(!nodeName.isEmpty())
{
nameElement = typeElement.firstChildElement(nodeName);
}
optionElement = nameElement.firstChildElement(optionName);
if(optionElement.isNull())
{
//the option did not exist: no need to clear!
return;
}
else
nameElement.removeChild(optionElement);
saveConfig(configFile->fileName());
//TODO: need to emit this change and deal with it.
}
int MachineConfig::getNumOptions(const QString & nodeType, const QString & nodeName) const
{
QDomElement typeElement;
QDomElement nameElement;
if(nodeName.isEmpty())
{
nameElement = root.firstChildElement(nodeType);
}
else
{
typeElement = root.firstChildElement(nodeType);
if(nodeName == "*")
nameElement = typeElement.firstChildElement();
else
nameElement = typeElement.firstChildElement(nodeName);
}
return nameElement.childNodes().size();
}
| 7,198
|
C++
|
.cpp
| 216
| 28.287037
| 139
| 0.68617
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,088
|
networkpage.cpp
|
uwolfer_qtemu/networkpage.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "networkpage.h"
#include "machineconfigobject.h"
#include "interfacemodel.h"
/****************************************************************************
** C++ Implementation: networkpage
**
** Description:
**
****************************************************************************/
NetworkPage::NetworkPage(MachineConfigObject *config, QWidget *parent)
: QWidget(parent)
, config(config)
, changingSelection(false)
{
setupUi(this);
setupModels();
makeConnections();
registerObjects();
}
NetworkPage::~NetworkPage()
{
}
void NetworkPage::changeNetPage(bool state)
{
networkStack->setCurrentIndex((int)state);
}
void NetworkPage::makeConnections()
{
connect(advancedButton, SIGNAL(toggled(bool)), this, SLOT(changeNetPage(bool)));
//guest
connect(addGuest, SIGNAL(clicked()), this, SLOT(addGuestInterface()));
connect(delGuest, SIGNAL(clicked()), this, SLOT(delGuestInterface()));
connect(guestView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(guestSelectionChanged(const QItemSelection &, const QItemSelection &)));
//host
connect(addHost, SIGNAL(clicked()), this, SLOT(addHostInterface()));
connect(delHost, SIGNAL(clicked()), this, SLOT(delHostInterface()));
connect(hostView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(hostSelectionChanged(const QItemSelection &, const QItemSelection &)));
}
void NetworkPage::setupModels()
{
guestModel = new GuestInterfaceModel(config, this);
guestView->setModel(guestModel);
hostModel = new HostInterfaceModel(config, this);
hostView->setModel(hostModel);
hostInterface->setModel(hostModel);
}
void NetworkPage::registerObjects()
{
config->registerObject(networkCheck, "network", QVariant(true));
config->registerObject(networkEdit, "networkCustomOptions");
config->registerObject(advancedButton, "netAdvanced", QVariant(false));
config->registerObject(easyModeBox, "net-host", "host0", "type");
config->registerObject(easyMacEdit, "net-guest", "guest0", "mac");
config->registerObject(accelCheck, "net-guest", "guest0", "nic");
}
void NetworkPage::addGuestInterface()
{
guestModel->insertRows(guestModel->rowCount(), 1);
}
void NetworkPage::delGuestInterface()
{
if(guestView->selectionModel()->selectedIndexes().size() !=0)
{
guestModel->removeRows(guestView->selectionModel()->selectedIndexes().first().row(), guestView->selectionModel()->selectedRows(0).size());
}
}
void NetworkPage::addHostInterface()
{
hostModel->insertRows(hostModel->rowCount(), 1);
hostTypeBox->setCurrentIndex(0);
}
void NetworkPage::delHostInterface()
{
if(hostView->selectionModel()->selectedIndexes().size() !=0)
hostModel->removeRows(hostView->selectionModel()->selectedIndexes().first().row(), hostView->selectionModel()->selectedRows(0).size());
}
void NetworkPage::guestSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected)
{
if (changingSelection)
return;
changingSelection=true;
//change host selection to none
hostView->selectionModel()->clearSelection();
//disconnect other interfaces
config->unregisterObject(nicModelCombo);
config->unregisterObject(macEdit);
config->unregisterObject(randomCheck);
config->unregisterObject(hostInterface);
if(guestView->selectionModel()->selectedIndexes().size() == 0)
{
propertyStack->setCurrentIndex(6);
changingSelection=false;
return;
}
QString rowName = guestModel->rowName(selected.first().indexes().first().row());
//show guest properties
propertyStack->setCurrentIndex(5);
//populate guest properties
config->registerObject(nicModelCombo, "net-guest", rowName, "nic");
config->registerObject(macEdit, "net-guest", rowName, "mac");
config->registerObject(randomCheck, "net-guest", rowName, "randomize");
config->registerObject(hostInterface, "net-guest", rowName, "host");
changingSelection=false;
}
void NetworkPage::hostSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected)
{
if(changingSelection)
return;
changingSelection=true;
//change guest selection to none
guestView->selectionModel()->clearSelection();
//disconnect other interfaces
config->unregisterObject(interfaceEdit);
config->unregisterObject(interfaceEdit_2);
config->unregisterObject(interfaceEdit_3);
config->unregisterObject(bridgeEdit);
config->unregisterObject(hardwareEdit);
config->unregisterObject(hardwareEdit_2);
config->unregisterObject(spanningCheck);
config->unregisterObject(upScriptEdit);
config->unregisterObject(downScriptEdit);
config->unregisterObject(hostnameEdit);
config->unregisterObject(tftpCheck);
config->unregisterObject(tftpEdit);
config->unregisterObject(bootpCheck);
config->unregisterObject(bootpEdit);
config->unregisterObject(udpButton);
config->unregisterObject(tcpButton);
config->unregisterObject(addressCombo);
config->unregisterObject(portSpin);
config->unregisterObject(hostTypeBox);
if(hostModel->rowCount(QModelIndex()) == 0 || hostView->selectionModel()->selectedIndexes().size() == 0)
{
propertyStack->setCurrentIndex(6);
changingSelection=false;
return;
}
QString rowName = hostModel->rowName(selected.first().indexes().first().row());
config->registerObject(hostTypeBox, "net-host", rowName, "type", "User Mode");
propertyStack->setCurrentIndex(hostTypeBox->currentIndex());
config->registerObject(interfaceEdit, "net-host", rowName, "interface");
config->registerObject(interfaceEdit_2, "net-host", rowName, "interface");
config->registerObject(interfaceEdit_3, "net-host", rowName, "interface");
config->registerObject(bridgeEdit, "net-host", rowName, "bridgeInterface");
config->registerObject(hardwareEdit, "net-host", rowName, "hardwareInterface");
config->registerObject(hardwareEdit_2, "net-host", rowName, "hardwareInterface");
config->registerObject(spanningCheck, "net-host", rowName, "spanningTree");
config->registerObject(upScriptEdit, "net-host", rowName, "ifUp");
config->registerObject(downScriptEdit, "net-host", rowName, "ifDown");
config->registerObject(hostnameEdit, "net-host", rowName, "hostname");
config->registerObject(tftpCheck, "net-host", rowName, "tftp");
config->registerObject(tftpEdit, "net-host", rowName, "tftpPath");
config->registerObject(bootpCheck, "net-host", rowName, "bootp");
config->registerObject(bootpEdit, "net-host", rowName, "bootpPath");
config->registerObject(udpButton, "net-host", rowName, "vlanType");
config->registerObject(tcpButton, "net-host", rowName, "vlanType");
config->registerObject(addressCombo, "net-host", rowName, "address");
config->registerObject(portSpin, "net-host", rowName, "port");
changingSelection=false;
}
void NetworkPage::loadHostEthIfs()
{
//we will load ethernet interfaces from HAL and insert them.
hardwareEdit->addItem("eth0");
hardwareEdit_2->addItem("eth0");
}
| 8,296
|
C++
|
.cpp
| 188
| 40.164894
| 198
| 0.713346
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,089
|
usbmodel.cpp
|
uwolfer_qtemu/usbmodel.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "usbmodel.h"
#include "machineconfigobject.h"
#include "halobject.h"
#include "qtemuenvironment.h"
#include <QStringList>
#include <QStandardItem>
UsbModel::UsbModel(MachineConfigObject * config, QObject * parent)
:QStandardItemModel(parent)
,config(config)
{
hal = QtEmuEnvironment::getHal();
getUsbDevices();
loadConfig();
connect(this, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(getChange(QStandardItem*)));
connect(hal, SIGNAL(usbAdded(QString,UsbDevice)), this, SLOT(deviceAdded(QString,UsbDevice)));
connect(hal, SIGNAL(usbRemoved(QString,UsbDevice)), this, SLOT(deviceRemoved(QString,UsbDevice)));
}
void UsbModel::getUsbDevices()
{
QList<UsbDevice> deviceList = hal->usbList();
if (!deviceList.isEmpty())
{
clear();
for(int i = 0; i < deviceList.size(); i++)
{
addItem(deviceList.at(i).vendor + " - " + deviceList.at(i).product, deviceList.at(i).id);
}
}
}
void UsbModel::addItem(const QString deviceName, QString id)
{
#ifdef DEVELOPER
qDebug(QString(deviceName + ' ' + id).toAscii());
#endif
QList<QStandardItem*> items;
items.append(new QStandardItem(deviceName));
id.remove("/org/freedesktop/Hal/devices/usb_device_");
items.append(new QStandardItem(id));
items.at(0)->setCheckable(true);
appendRow(items);
//appendRow(QStandardItem(deviceName).setData(id));
}
void UsbModel::loadConfig()
{
QStringList names = config->getConfig()->getAllOptionNames("usb", "");
for(int i=0;i<names.size();i++)
{
if(names.at(i).contains("host"))
checkDevice(config->getOption("usb", names.at(i),"id",QString()).toString());
}
}
void UsbModel::checkDevice(QString deviceName)
{
for(int i = 0; i < rowCount(QModelIndex()); i++)
{
if(item(i,1)->text() == deviceName)
{
item(i,0)->setCheckState(Qt::Checked);
break;
}
}
}
void UsbModel::getChange(QStandardItem * thisItem)
{
QStringList names = config->getConfig()->getAllOptionNames("usb", "");
QString nextFreeName;
QString address;
//find the next free name for a usb host device
for(int i = 0; i < names.size() + 1;i++)
{
if(!names.contains("host" + QString::number(i)))
{
nextFreeName = "host" + QString::number(i);
}
}
for(int i = 0; i < rowCount(QModelIndex()); i++)
{
if(item(i,0)->text() == thisItem->text())
{
if(thisItem->checkState() == Qt::Checked)
{
address = hal->usbList().at(i).address;
bool checkExists = false;
for(int j = 0; j< names.size(); j++)
{
if(config->getOption("usb", names.at(j), "id", QString()) == item(i,1)->text())
{
config->setOption("usb", names.at(j), "address", address);
emit(vmDeviceAdded(address));
checkExists = true;
break;
}
}
if(!checkExists)
{
config->setOption("usb", nextFreeName, "id", item(i,1)->text());
config->setOption("usb", nextFreeName, "address", address);
emit(vmDeviceAdded(address));
}
}
else
{
for(int j = 0; j < names.size(); j++)
{
if(config->getOption("usb", names.at(j), "id", QString()) == item(i,1)->text())
{
emit(vmDeviceRemoved(config->getOption("usb", names.at(j), "address", "0.0").toString()));
config->getConfig()->clearOption("usb", names.at(j), "id");
config->getConfig()->clearOption("usb", names.at(j), "address");
config->getConfig()->clearOption("usb","",names.at(j));
}
}
}
break;
}
}
}
void UsbModel::deviceAdded(QString name, UsbDevice device)
{
#ifdef DEVELOPER
qDebug(QString("device added " + device.vendor + '-' + device.product + device.id).toAscii());
#endif
QString id = device.id;
addItem(device.vendor + " - " + device.product, id.remove("/org/freedesktop/Hal/devices/usb_device_"));
loadConfig();
if(property("autoAddDevices").toBool())
{
for(int i=0;i<this->rowCount(QModelIndex());i++)
{
if((QString("/org/freedesktop/Hal/devices/usb_device_") + QString(item(i,1)->text())) == name)
{
item(i,0)->setCheckState(Qt::Checked);
}
}
}
}
void UsbModel::deviceRemoved(QString name, UsbDevice device)
{
for(int i=0;i<this->rowCount(QModelIndex());i++)
{
if((QString("/org/freedesktop/Hal/devices/usb_device_") + QString(item(i,1)->text())) == name)
{
#ifdef DEVELOPER
qDebug("device removed " + name.toAscii());
#endif
this->removeRow(i);
//getUsbDevices();
loadConfig();
break;
}
}
}
| 6,224
|
C++
|
.cpp
| 174
| 27.971264
| 114
| 0.567115
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,090
|
machinetab.cpp
|
uwolfer_qtemu/machinetab.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machinetab.h"
#include "machineprocess.h"
#include "config.h"
#include "machineview.h"
#include "settingstab.h"
#include "harddiskmanager.h"
#include "controlpanel.h"
#include "guesttoolslistener.h"
#include <QMessageBox>
#include <QPushButton>
#include <QLineEdit>
#include <QTabWidget>
#include <QFile>
#include <QCheckBox>
#include <QSlider>
#include <QTextEdit>
#include <QSpinBox>
#include <QFileDialog>
#include <QTextStream>
#include <QRadioButton>
#include <QVBoxLayout>
#include <QLabel>
#include <QSettings>
#include <QFileInfo>
#include <QMenu>
#include <QButtonGroup>
#include <QTimer>
#include <QResizeEvent>
#include <QScrollArea>
#include <QUrl>
#include <QToolButton>
#include <QAction>
MachineTab::MachineTab(QTabWidget *parent, const QString &fileName, const QString &myMachinesPathParent)
: QWidget(parent)
{
parentTabWidget = parent;
xmlFileName = fileName;
myMachinesPath = myMachinesPathParent;
QSettings settings("QtEmu", "QtEmu");
QString iconTheme = settings.value("iconTheme", "oxygen").toString();
machineConfig = new MachineConfig(this, fileName);
machineConfigObject = new MachineConfigObject(this, machineConfig);
machineView = new MachineView(machineConfigObject, this);
machineProcess = new MachineProcess(this);
machineConfigObject->setOption("vncPort", 1000 + parentTabWidget->currentIndex() + 1);
settingsTab = new SettingsTab(machineConfigObject, this);
machineNameEdit = new QLineEdit(this);
guestToolsListener = new GuestToolsListener(machineConfigObject->getOption("hdd",QString()).toString().replace(QRegExp("[.][^.]+$"), ".tools"), this);
#ifndef Q_OS_WIN32
const QString flatStyle = QString("TYPE { border: 2px solid transparent;"
"background-color: transparent; }"
"TYPE:hover { background-color: white;"
"border: 2px inset %1; border-radius: 3px;}"
"TYPE:focus { background-color: white;"
"border: 2px inset %2; border-radius: 3px;}")
.arg(machineNameEdit->palette().color(QPalette::Mid).name())
.arg(machineNameEdit->palette().color(QPalette::Highlight).name());
#elif defined(Q_OS_WIN32)
const QString flatStyle = QString("TYPE { border: 1px solid transparent;"
"background-color: transparent; }"
"TYPE:hover, TYPE:focus { background-color: white;"
"border: 1px solid %1;}")
.arg(machineNameEdit->palette().color(QPalette::Highlight).name());
#endif
#if QT_VERSION >= 0x040200
machineNameEdit->setStyleSheet(QString(flatStyle).replace("TYPE", "QLineEdit")
+"QLineEdit { font: bold 16px; }");
#endif
QPushButton *closeButton = new QPushButton(QIcon(":/images/" + iconTheme + "/close.png"), QString(), this);
closeButton->setFlat(true);
closeButton->setToolTip(tr("Close this machine"));
connect(closeButton, SIGNAL(clicked(bool)), this, SLOT(closeMachine()));
QHBoxLayout *closeButtonLayout = new QHBoxLayout;
closeButtonLayout->addWidget(machineNameEdit);
closeButtonLayout->addWidget(closeButton);
startButton = new QPushButton(QIcon(":/images/" + iconTheme + "/start.png"), tr("&Start"), this);
startButton->setWhatsThis(tr("Start this virtual machine"));
startButton->setIconSize(QSize(22, 22));
connect(startButton, SIGNAL(clicked(bool)), this, SLOT(start()));
QMenu *stopMenu = new QMenu();
QAction *stopAction = stopMenu->addAction(QIcon(":/images/" + iconTheme + "/stop.png"), tr("&Shutdown"));
QAction *forceAction = stopMenu->addAction(QIcon(":/images/" + iconTheme + "/force.png"), tr("&Force Poweroff"));
stopAction->setWhatsThis(tr("Tell this virtual machine to shut down"));
forceAction->setWhatsThis(tr("Force this virtual machine to stop immediately"));
stopButton = new QPushButton(this);
stopButton->setToolTip(tr("Hold down this button for additional options"));
stopButton->setMenu(stopMenu);
// stopButton->setDefaultAction(stopAction);
stopButton->setIcon(QIcon(":/images/" + iconTheme + "/stop.png"));
// stopButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
stopButton->setIconSize(QSize(22, 22));
stopButton->setSizePolicy(startButton->sizePolicy());
stopButton->setText(tr("&Stop"));
stopButton->setEnabled(false);
connect(stopAction, SIGNAL(triggered(bool)), machineProcess, SLOT(stop()));
connect(forceAction, SIGNAL(triggered(bool)), this, SLOT(forceStop()));
QHBoxLayout *powerButtonsLayout = new QHBoxLayout;
powerButtonsLayout->addWidget(startButton);
powerButtonsLayout->addWidget(stopButton);
suspendButton = new QPushButton(QIcon(":/images/" + iconTheme + "/suspend.png"), tr("&Suspend"), this);
suspendButton->setWhatsThis(tr("Suspend this virtual machine"));
suspendButton->setIconSize(QSize(22, 22));
connect(suspendButton, SIGNAL(clicked(bool)), machineProcess, SLOT(suspend()));
suspendButton->setHidden(true);
suspendButton->setEnabled(false);
resumeButton = new QPushButton(QIcon(":/images/" + iconTheme + "/resume.png"), tr("&Resume"), this);
resumeButton->setWhatsThis(tr("Resume this virtual machine"));
resumeButton->setIconSize(QSize(22, 22));
connect(resumeButton, SIGNAL(clicked(bool)), machineProcess, SLOT(resume()));
resumeButton->setEnabled(false);
pauseButton = new QPushButton(QIcon(":/images/" + iconTheme + "/pause.png"), tr("&Pause"), this);
pauseButton->setWhatsThis(tr("Pause/Unpause this virtual machine"));
pauseButton->setCheckable(true);
pauseButton->setIconSize(QSize(22, 22));
pauseButton->setEnabled(false);
connect(pauseButton, SIGNAL(clicked(bool)), machineProcess, SLOT(togglePause()));
QHBoxLayout *controlButtonsLayout = new QHBoxLayout;
controlButtonsLayout->addWidget(suspendButton);
controlButtonsLayout->addWidget(resumeButton);
controlButtonsLayout->addWidget(pauseButton);
snapshotCheckBox = new QCheckBox(tr("Snapshot mode"), this);
connect(snapshotCheckBox, SIGNAL(stateChanged(int)), this, SLOT(snapshot(int)));
QToolButton *screenshotButton = new QToolButton(this);
screenshotButton->setAutoRaise(false);
screenshotButton->setIcon(QIcon(":/images/" + iconTheme + "/camera.png"));
screenshotButton->setIconSize(QSize(22, 22));
screenshotButton->setToolTip(tr("Set preview screenshot"));
QHBoxLayout *snapshotLayout = new QHBoxLayout;
snapshotLayout->addWidget(snapshotCheckBox);
snapshotLayout->addWidget(screenshotButton);
connect(screenshotButton, SIGNAL(clicked()), this, SLOT(takeScreenshot()));
QLabel *notesLabel = new QLabel(tr("<strong>Notes</strong>"), this);
notesTextEdit = new QTextEdit(this);
notesTextEdit->setFixedHeight(60);
#if QT_VERSION >= 0x040200
notesTextEdit->setStyleSheet(QString(flatStyle).replace("TYPE", "QTextEdit"));
#endif
QLabel *controlLabel = new QLabel(tr("<strong>Control Panel</strong>"), this);
controlPanel = new ControlPanel(this);
QVBoxLayout *buttonsLayout = new QVBoxLayout();
buttonsLayout->addLayout(closeButtonLayout);
buttonsLayout->addLayout(powerButtonsLayout);
buttonsLayout->addLayout(controlButtonsLayout);
buttonsLayout->addLayout(snapshotLayout);
buttonsLayout->addWidget(notesLabel);
buttonsLayout->addWidget(notesTextEdit);
buttonsLayout->addStretch(10);
buttonsLayout->addWidget(controlLabel);
buttonsLayout->addWidget(controlPanel);
//set up the layout for the tab panel
QGridLayout *mainLayout = new QGridLayout(this);
mainLayout->addLayout(buttonsLayout, 0, 0);
QTabWidget *viewTabs = new QTabWidget(this);
mainLayout->addWidget(viewTabs, 0, 1);
mainLayout->setColumnStretch(1, 10);
viewTabs->addTab(machineView, tr("Display"));
machineConfigObject->registerObject(machineView);
viewTabs->addTab(settingsTab, tr("Settings"));
//console area
consoleFrame = new QFrame(this);
viewTabs->addTab(consoleFrame, tr("Console"));
console = new QTextEdit(this);
console->setReadOnly(true);
connect(machineProcess, SIGNAL(cleanConsole(QString)), console, SLOT(append(QString)));
consoleCommand = new QLineEdit(this);
//console->setFocusProxy(consoleCommand);
QPushButton *consoleCommandButton = new QPushButton(tr("Enter Command"), this);
connect(consoleCommand, SIGNAL(returnPressed()),
consoleCommandButton, SLOT(click()));
connect(consoleCommandButton, SIGNAL(clicked()), this, SLOT(runCommand()));
QVBoxLayout *consoleLayout = new QVBoxLayout();
QHBoxLayout *consoleCommandLayout = new QHBoxLayout();
consoleLayout->addWidget(console);
consoleCommandLayout->addWidget(consoleCommand);
consoleCommandLayout->addWidget(consoleCommandButton);
consoleLayout->addLayout(consoleCommandLayout);
consoleFrame->setLayout(consoleLayout);
setLayout(mainLayout);
consoleFrame->setAutoFillBackground (true);
settingsTab->setAutoFillBackground (true);
//end console area
read();
//read first the name, otherwise the name of the main tab changes
makeConnections();
machineProcess->getHdManager()->testImage();
machineProcess->connectIfRunning();
}
bool MachineTab::read()
{
//init and register values
machineConfigObject->registerObject(machineNameEdit, "name");
machineConfigObject->registerObject(snapshotCheckBox, "snapshot", QVariant(false));
#ifdef DEVELOPER
machineConfigObject->setOption("snapshot", true);
#endif
machineConfigObject->registerObject(notesTextEdit, "notes");
return true;
}
void MachineTab::nameChanged(const QString &name)
{
parentTabWidget->setTabText(parentTabWidget->currentIndex(), name);
}
QString MachineTab::machineName()
{
return machineNameEdit->text();
}
void MachineTab::closeMachine()
{
if (QMessageBox::question(this, tr("Close confirmation"),
tr("Are you sure you want to close this machine?<br />"
"You can open it again with the corresponding .qte file in your \"MyMachines\" folder."),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::No)
== QMessageBox::Yes)
parentTabWidget->removeTab(parentTabWidget->currentIndex());
}
void MachineTab::start()
{
console->clear();
machineProcess->start();
}
void MachineTab::suspending()
{
//startButton->setEnabled(false);
//stopButton->setEnabled(false);
//suspendButton->setEnabled(false);
//pauseButton->setEnabled(false);
setEnabled(false);
//TODO: start a progress bar
}
void MachineTab::suspended()
{
machineProcess->forceStop();
//resumeButton->setHidden(false);
machineProcess->getHdManager()->testImage();
suspendButton->setHidden(true);
setEnabled(true);
//stop the progress bar
}
void MachineTab::resuming()
{
//startButton->setEnabled(false);
//stopButton->setEnabled(false);
setEnabled(false);
}
void MachineTab::resumed()
{
setEnabled(true);
startButton->setEnabled(false);
stopButton->setEnabled(true);
suspendButton->setHidden(false);
resumeButton->setHidden(true);
//this is kinda sucky, i think it's a qemu bug.
QMessageBox::information(this, tr("Resume"),
tr("Your machine is being resumed. USB devices will not function properly on Windows. You must reload<br />the USB driver to use your usb devices including the seamless mouse.<br />In addition the advanced VGA adapter will not refresh initially on any OS."));
}
void MachineTab::forceStop()
{
QMessageBox msgBox;
msgBox.setText(tr("This will force the current machine to power down. Are you sure?<br />"
"You should only do this if the machine is unresponsive or does not support ACPI. Doing this may cause damage to the disk image."));
msgBox.setStandardButtons(QMessageBox::Cancel);
QPushButton *forceShutdownButton = msgBox.addButton(tr("Force Power Off"), QMessageBox::DestructiveRole);
msgBox.setDefaultButton(QMessageBox::Cancel);
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
if (msgBox.clickedButton()==forceShutdownButton)
machineProcess->forceStop();
}
void MachineTab::finished()
{
stopButton->setEnabled(false);
startButton->setEnabled(true);
pauseButton->setEnabled(false);
resumeButton->setHidden(false);
suspendButton->setHidden(true);
snapshotCheckBox->setText(tr("Snapshot mode"));
cleanupView();
machineProcess->getHdManager()->testImage();
shownErrors.clear();
}
void MachineTab::started()
{
}
void MachineTab::error(const QString & errorMsg)
{
if (errorMsg.contains("(VMDK)"))
{
//for some reason qemu throws an error message when using a VMDK image. oh well... it isn't a REAL error, so ignore it.
return;
}
else if (errorMsg.contains("bind()"))
{
if( QMessageBox::critical(this, tr("QtEmu machine already running!"), tr("There is already a virtual machine running on the specified<br />"
"VNC port or file. This may mean a previous QtEmu session crashed; <br />"
"if this is the case you can try to connect to the virtual machine <br />"
"to rescue your data and shut it down safely.<br /><br />"
"Try to connect to this machine?"),QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
{
QTimer::singleShot(500, machineView, SLOT(initView()));
}
return;
}
else if ((!shownErrors.contains("audio"))&&(errorMsg.contains("audio:")))
{
shownErrors << "audio";
QMessageBox::critical(this, tr("QtEmu Sound Error"), tr("QtEmu is having trouble accessing your sound system. Make sure<br />"
"you have your host sound system selected correctly in the Sound<br />"
"section of the settings tab. Also make sure your version of <br />"
"qemu/KVM has support for the sound system you selected.")
,QMessageBox::Ok);
return;
}
QMessageBox::critical(this, tr("QtEmu Error"), tr("An error has occurred. This may have been caused by<br />"
"an incorrect setting. The error is:<br />") + errorMsg,QMessageBox::Ok);
}
void MachineTab::snapshot(const int state)
{
if(state == Qt::Unchecked)
{
snapshotCheckBox->setText(tr("Snapshot mode"));
}
}
void MachineTab::runCommand()
{
machineProcess->write(consoleCommand->text().toAscii() + '\n');
consoleCommand->clear();
}
void MachineTab::restart()
{
connect(machineProcess, SIGNAL(finished(int)) , this, SLOT(clearRestart()));
machineProcess->stop();
}
void MachineTab::clearRestart()
{
disconnect(machineProcess, SIGNAL(finished(int)) , this, SLOT(clearRestart()));
startButton->click();
}
void MachineTab::booting()
{
if(machineConfigObject->getOption("embeddedDisplay",QVariant(false)).toBool())
machineView->initView();
if(snapshotCheckBox->isChecked())
{
snapshotCheckBox->setText(snapshotCheckBox->text() + '\n' + tr("(uncheck to commit changes)"));
}
pauseButton->setEnabled(true);
suspendButton->setHidden(false);
resumeButton->setHidden(true);
startButton->setEnabled(false);
stopButton->setEnabled(true);
delete(guestToolsListener);
guestToolsListener = new GuestToolsListener(machineConfigObject->getOption("hdd",QString()).toString().replace(QRegExp("[.][^.]+$"), ".tools"), this);
}
void MachineTab::cleanupView()
{
machineView->showSplash(true);
}
void MachineTab::takeScreenshot()
{
QString fileName = machineConfigObject->getOption("hdd",QString()).toString().replace(QRegExp("[.][^.]+$"), ".ppm");
machineProcess->write(QString("screendump " + fileName).toAscii() + '\n');
machineConfigObject->setOption("preview", fileName);
}
void MachineTab::makeConnections()
{
connect(machineNameEdit, SIGNAL(textChanged(const QString&)), this, SLOT(nameChanged(QString)));
//hard disk manager related connections
HardDiskManager *hdManager = machineProcess->getHdManager();
connect(settingsTab, SIGNAL(upgradeHdd()), hdManager, SLOT(upgradeImage()));
connect(hdManager, SIGNAL(imageUpgradable(bool)), settingsTab->upgradeFrame, SLOT(setEnabled(bool)));
connect(hdManager, SIGNAL(processingImage(bool)), this, SLOT(setDisabled(bool)));
connect(hdManager, SIGNAL(error(const QString&)), this, SLOT(error(const QString&)));
connect(hdManager, SIGNAL(imageFormat(QString)), settingsTab->formatLabel, SLOT(setText(QString)));
connect(hdManager, SIGNAL(imageSize(qint64)), settingsTab, SLOT(setVirtSize(qint64)));
connect(hdManager, SIGNAL(phySize(qint64)), settingsTab, SLOT(setPhySize(qint64)));
connect(hdManager, SIGNAL(supportsSuspending(bool)), suspendButton, SLOT(setEnabled(bool)));
connect(hdManager, SIGNAL(supportsResuming(bool)), resumeButton, SLOT(setEnabled(bool)));
}
| 18,978
|
C++
|
.cpp
| 401
| 40.381546
| 288
| 0.680243
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,091
|
mainwindow.cpp
|
uwolfer_qtemu/mainwindow.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "mainwindow.h"
#include "machinetab.h"
#include "machinewizard.h"
#include "helpwindow.h"
#include "configwindow.h"
#include "config.h"
#include "machineprocess.h"
#include <QSettings>
#include <QTabWidget>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QIcon>
#include <QAction>
#include <QCloseEvent>
#include <QFileDialog>
#include <QTimer>
#include <QMenuBar>
#include <QVBoxLayout>
#include <QLabel>
#include <QStatusBar>
#include <QToolBar>
#include <QMessageBox>
#include <QToolButton>
MainWindow::MainWindow()
{
QSettings settings("QtEmu", "QtEmu");
iconTheme = settings.value("iconTheme", "oxygen").toString();
setWindowTitle(tr("QtEmu"));
setWindowIcon(QPixmap(":/images/" + iconTheme + "/qtemu.png"));
tabWidget = new QTabWidget;
tabWidget->setTabPosition(QTabWidget::West);
setCentralWidget(tabWidget);
createActions();
createMenus();
createToolBars();
createStatusBar();
createMainTab();
readSettings();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
int runningMachines = 0;
int savingMachines = 0;
for (int i = 1; i<(tabWidget->count());i++)
{
MachineTab *tab = static_cast<MachineTab *>(tabWidget->widget(i));
if(tab->machineProcess->state() == MachineProcess::Running)
{
runningMachines++;
}
else if(tab->machineProcess->state() == MachineProcess::Saving)
{
savingMachines++;
}
}
if (savingMachines != 0)
{
QMessageBox::critical(this, tr("Virtual Machine Saving State!"),
tr("You have virtual machines currently saving their state.<br />"
"Quitting now would very likely damage your Virtual Machine!!"),
QMessageBox::Cancel);
event->ignore();
return;
}
if (runningMachines == 0 || QMessageBox::question(this, tr("Exit confirmation"),
tr("You have virtual machines currently running. Are you sure you want to quit?<br />"
"Quitting QtEmu will leave your virtual machines running. QtEmu will<br />"
"automatically reconnect to your virtual machines next time you run it."),
QMessageBox::Close | QMessageBox::Cancel, QMessageBox::Cancel)
== QMessageBox::Close)
{
writeSettings();
event->accept();
}
else
{
event->ignore();
}
}
void MainWindow::createNew()
{
QString machine = MachineWizard::newMachine(myMachinesPath, this);
if (!machine.isEmpty())
loadFile(machine);
}
void MainWindow::open()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a virtual machine"),
myMachinesPath,
tr("QtEmu machines")+" (*.qte)");
if (!fileName.isEmpty())
loadFile(fileName);
}
void MainWindow::configure()
{
ConfigWindow *config = new ConfigWindow(myMachinesPath, tabWidget->tabPosition(), this);
if (config->exec() == QDialog::Accepted)
{
myMachinesPath = config->myMachinePathLineEdit->text();
QTabWidget::TabPosition position;
switch(config->comboTabPosition->currentIndex())
{
case 0: position = QTabWidget::North;
break;
case 1: position = QTabWidget::South;
break;
case 2: position = QTabWidget::West;
break;
case 3: position = QTabWidget::East;
break;
default: position = QTabWidget::West;
}
tabWidget->setTabPosition(position);
}
}
void MainWindow::start()
{
MachineTab *tab = qobject_cast<MachineTab *>(tabWidget->currentWidget());
QPushButton *startButton = qobject_cast<QPushButton *>(tab->startButton);
startButton->click();
}
void MainWindow::pause()
{
MachineTab *tab = qobject_cast<MachineTab *>(tabWidget->currentWidget());
QPushButton *pauseButton = qobject_cast<QPushButton *>(tab->pauseButton);
pauseButton->click();
}
void MainWindow::stop()
{
MachineTab *tab = qobject_cast<MachineTab *>(tabWidget->currentWidget());
QPushButton *stopButton = qobject_cast<QPushButton *>(tab->stopButton);
stopButton->click();
}
void MainWindow::restart()
{
//stop();
//QTimer::singleShot(500, this, SLOT(start()));
MachineTab *tab = qobject_cast<MachineTab *>(tabWidget->currentWidget());
tab->restart();
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About QtEmu"),
tr("<h2>QtEmu</h2>Version %1<br>"
"<b><i>QtEmu</i></b> is a graphical user interface for "
"<a href=http://qemu.org>QEMU</a>.<br><br>Copyright © "
"2006-2009 Urs Wolfer <a href=mailto:uwolfer%2fwo.ch>uwolfer%2fwo.ch</a>.<br />"
"Copyright © 2008-2009 Ben Klopfenstein <a href=mailto:benklop%2gmail.com>benklop%2gmail.com</a>.<br />"
"All rights reserved.<br><br>"
"The program is provided AS IS with NO WARRANTY OF ANY KIND.<br><br>"
"The icons have been taken from the KDE Crystal and Oxygen themes which are LGPL licensed.")
.arg(VERSION).arg("@"));
}
void MainWindow::help()
{
HelpWindow *help = new HelpWindow(this);
help->show();
help->raise();
help->activateWindow();
}
void MainWindow::createActions()
{
//file actions
newAct = new QAction(QIcon(":/images/" + iconTheme + "/new.png"), tr("&New Machine"), this);
newAct->setShortcut(tr("Ctrl+N"));
newAct->setStatusTip(tr("Create a new machine"));
connect(newAct, SIGNAL(triggered()), this, SLOT(createNew()));
openAct = new QAction(QIcon(":/images/" + iconTheme + "/open.png"), tr("&Open Machine..."), this);
openAct->setShortcut(tr("Ctrl+O"));
openAct->setStatusTip(tr("Open an existing machine"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
confAct = new QAction(tr("Confi&gure"), this);
confAct->setShortcut(tr("Ctrl+G"));
confAct->setStatusTip(tr("Customize the application"));
connect(confAct, SIGNAL(triggered()), this, SLOT(configure()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit the application"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
//power actions
startAct = new QAction(QIcon(":/images/" + iconTheme + "/start.png"), tr("&Start"), this);
startAct->setShortcut(tr("Ctrl+S"));
startAct->setStatusTip(tr("Start this virtual machine"));
startAct->setEnabled(false);
connect(startAct, SIGNAL(triggered()), this, SLOT(start()));
stopAct = new QAction(QIcon(":/images/" + iconTheme + "/stop.png"), tr("S&top"), this);
stopAct->setShortcut(tr("Ctrl+T"));
stopAct->setStatusTip(tr("Kill this machine"));
stopAct->setEnabled(false);
connect(stopAct, SIGNAL(triggered()), this, SLOT(stop()));
restartAct = new QAction(QIcon(":/images/" + iconTheme + "/restart.png"), tr("&Restart"), this);
restartAct->setShortcut(tr("Ctrl+R"));
restartAct->setStatusTip(tr("Restart this machine"));
restartAct->setEnabled(false);
connect(restartAct, SIGNAL(triggered()), this, SLOT(restart()));
pauseAct = new QAction(QIcon(":/images/" + iconTheme + "/pause.png"), tr("&Pause"), this);
pauseAct->setShortcut(tr("Ctrl+P"));
pauseAct->setStatusTip(tr("Pause this machine"));
pauseAct->setEnabled(false);
connect(pauseAct, SIGNAL(triggered()), this, SLOT(pause()));
helpAct = new QAction(tr("QtEmu &Help "), this);
helpAct->setShortcut(tr("F1"));
helpAct->setStatusTip(tr("Show Help"));
connect(helpAct, SIGNAL(triggered()), this, SLOT(help()));
aboutAct = new QAction(tr("&About QtEmu"), this);
aboutAct->setStatusTip(tr("Show the About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(newAct);
fileMenu->addAction(openAct);
fileMenu->addSeparator();
fileMenu->addAction(confAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addSeparator();
powerMenu = menuBar()->addMenu(tr("&Power"));
powerMenu->addAction(startAct);
powerMenu->addAction(pauseAct);
powerMenu->addAction(stopAct);
powerMenu->addAction(restartAct);
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(helpAct);
helpMenu->addSeparator();
helpMenu->addAction(aboutAct);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("File"));
fileToolBar->addAction(newAct);
fileToolBar->addAction(openAct);
powerToolBar = addToolBar(tr("Power"));
powerToolBar->addAction(startAct);
powerToolBar->addAction(pauseAct);
powerToolBar->addAction(stopAct);
powerToolBar->addAction(restartAct);
}
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::createMainTab()
{
mainTabWidget = new QWidget();
mainTabLabel = new QLabel(mainTabWidget);
mainTabLabel->setText(tr("<h1>QtEmu</h1>"
"QtEmu is a graphical user interface for QEMU. It has the ability "
"to run operating systems virtually in a window on native systems."));
mainTabLabel->setWordWrap(true);
newButton = new QPushButton(mainTabWidget);
//newButton->setDefaultAction(newAct);
newButton->setIconSize(QSize(32, 32));
//newButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
//newButton->setAutoRaise(true);
newButton->setIcon(QIcon(":/images/" + iconTheme + "/new.png"));
newButton->setText(tr("Create a new virtual machine. A wizard will help you \n"
"prepare for a new operating system"));
connect(newButton, SIGNAL(clicked()), this, SLOT(createNew()));
openButton = new QPushButton(mainTabWidget);
//openButton->setDefaultAction(openAct);
openButton->setIconSize(QSize(32, 32));
//openButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
//openButton->setAutoRaise(true);
openButton->setIcon(QIcon(":/images/" + iconTheme + "/open.png"));
openButton->setText(tr("Open an existing virtual machine"));
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
QVBoxLayout *buttonLayout = new QVBoxLayout;
buttonLayout->setSpacing(20);
buttonLayout->addWidget(mainTabLabel);
buttonLayout->addWidget(newButton);
buttonLayout->addWidget(openButton);
buttonLayout->addStretch(1);
mainTabWidget->setLayout(buttonLayout);
tabWidget->addTab(mainTabWidget, QIcon(":/images/" + iconTheme + "/qtemu.png"), tr("Main"));
}
void MainWindow::readSettings()
{
QSettings settings("QtEmu", "QtEmu");
QPoint pos = settings.value("pos", QPoint(0, 50)).toPoint();
QSize size = settings.value("size", QSize(350, 700)).toSize();
resize(size);
move(pos);
myMachinesPath = settings.value("machinesPath", QString(QDir::homePath()+'/'+tr("MyMachines"))).toString();
QTabWidget::TabPosition position;
switch(settings.value("tabPosition", 2).toInt())
{
case 0: position = QTabWidget::North;
break;
case 1: position = QTabWidget::South;
break;
case 2: position = QTabWidget::West;
break;
case 3: position = QTabWidget::East;
break;
default: position = QTabWidget::West;
}
tabWidget->setTabPosition(position);
int countMachines = settings.beginReadArray("machines");
for (int i = 0; i < countMachines; ++i)
{
settings.setArrayIndex(i);
loadFile(settings.value("path").toString());
}
settings.endArray();
connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(changeMachineState(int)));
// workaround: check every second if user has finished machine with close button
QTimer *checkTimer = new QTimer(this);
connect(checkTimer, SIGNAL(timeout()), this, SLOT(changeMachineState()));
checkTimer->start(1000);
tabWidget->setCurrentIndex(settings.value("activeTab", 0).toInt());
}
void MainWindow::writeSettings()
{
QSettings settings("QtEmu", "QtEmu");
settings.setValue("pos", pos());
settings.setValue("size", size());
settings.setValue("machinesPath", myMachinesPath);
settings.setValue("tabPosition", tabWidget->tabPosition());
settings.beginWriteArray("machines");
for (int i = 1; i < tabWidget->count(); ++i) //do not start with the main tab
{
settings.setArrayIndex(i-1);
settings.setValue("path", tabWidget->tabToolTip(i));
}
settings.endArray();
settings.setValue("activeTab", tabWidget->currentIndex());
}
void MainWindow::loadFile(const QString &fileName)
{
MachineTab *machineTab = new MachineTab(tabWidget, fileName, myMachinesPath);
int index = tabWidget->addTab(machineTab, QIcon(":/images/" + iconTheme + "/qtemu.png"), machineTab->machineName());
tabWidget->setCurrentIndex(index);
tabWidget->setTabToolTip(index, fileName);
statusBar()->showMessage(tr("Machine loaded"), 2000);
}
void MainWindow::changeMachineState(int value)
{
if (tabWidget->currentIndex() != 0) //do not check the main tab
{
MachineTab *tab = qobject_cast<MachineTab *>(tabWidget->currentWidget());
QPushButton *startButton = qobject_cast<QPushButton *>(tab->startButton);
if (value != -1)
startButton->setFocus();
QPushButton *stopButton = qobject_cast<QPushButton *>(tab->stopButton);
connect(startButton, SIGNAL(clicked()), this, SLOT(changeMachineState()));
connect(stopButton, SIGNAL(clicked()), this, SLOT(changeMachineState()));
if (!startButton->isEnabled()&&tab->isEnabled())
{
stopAct->setEnabled(true);
pauseAct->setEnabled(true);
startAct->setEnabled(false);
restartAct->setEnabled(true);
}
else if (tab->isEnabled())
{
stopAct->setEnabled(false);
pauseAct->setEnabled(false);
startAct->setEnabled(true);
restartAct->setEnabled(false);
}
else
{
stopAct->setEnabled(false);
pauseAct->setEnabled(false);
startAct->setEnabled(false);
restartAct->setEnabled(false);
}
}
else //main tab is active
{
stopAct->setEnabled(false);
pauseAct->setEnabled(false);
startAct->setEnabled(false);
restartAct->setEnabled(false);
}
}
| 15,908
|
C++
|
.cpp
| 402
| 33.211443
| 124
| 0.647954
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,092
|
machinesplash.cpp
|
uwolfer_qtemu/machinesplash.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machinesplash.h"
#include <QImage>
#include <QSettings>
#include <QSvgRenderer>
#include <QSvgWidget>
#include <QLabel>
#include <QRectF>
#include <QVBoxLayout>
#include <QFrame>
#include <QDebug>
#include <QPixmap>
#include <QStyle>
MachineSplash::MachineSplash(QWidget *parent)
: QWidget(parent)
{
//set up splash background from splash.svg
QSettings settings("QtEmu", "QtEmu");
splashImage = new QSvgWidget(":/images/" + settings.value("iconTheme", "oxygen").toString() + "/splash.svg", this);
getPreviewRect();
previewImage = new QLabel(this);
alpha = QPixmap(":/images/" + settings.value("iconTheme", "oxygen").toString() + "/alpha.svg");
previewImage->setScaledContents(true);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(splashImage);
setLayout(layout);
doResize();
}
void MachineSplash::setPreview(const QString previewLocation)
{
if(!previewLocation.isEmpty())
previewLoc = previewLocation;
QPixmap preview = QPixmap(previewLoc);
preview.setAlphaChannel(alpha.scaled(preview.width(),preview.height()));
previewImage->setPixmap(preview);
doResize();
}
void MachineSplash::doResize()
{
getPreviewRect();
previewImage->setGeometry(previewBounds.toRect());
}
void MachineSplash::resizeEvent(QResizeEvent * event)
{
doResize();
QWidget::resizeEvent(event);
}
void MachineSplash::showEvent(QShowEvent * event)
{
doResize();
QWidget::showEvent(event);
}
void MachineSplash::getPreviewRect()
{
QRectF fullsizeBounds = splashImage->renderer()->boundsOnElement("QtEmu_Preview_Screen");
float scaleFactor =
splashImage->width() / splashImage->renderer()->viewBoxF().width();
previewBounds = QRectF(
fullsizeBounds.left()*scaleFactor,
fullsizeBounds.top()*scaleFactor,
fullsizeBounds.width()*scaleFactor,
fullsizeBounds.height()*scaleFactor
);
}
const QSize MachineSplash::sizeHint()
{
return splashImage->size();
}
| 3,031
|
C++
|
.cpp
| 89
| 31.067416
| 119
| 0.696618
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,093
|
settingstab.cpp
|
uwolfer_qtemu/settingstab.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "settingstab.h"
#include "machineconfigobject.h"
#include "helpwindow.h"
#include "networkpage.h"
#include "usbpage.h"
#include "qtemuenvironment.h"
#include "usbmodel.h"
#include "usbconfig.h"
#include <QIcon>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <QVBoxLayout>
SettingsTab::SettingsTab(MachineConfigObject *config, MachineTab *parent)
: QFrame(parent)
,config(config)
,parent(parent)
{
getSettings();
//add the ui elements
setupUi(this);
netPage = new NetworkPage(config, this);
networkPage->setLayout(new QVBoxLayout());
networkPage->layout()->addWidget(netPage);
usbPageWidget = new UsbPage(config, this);
usbPage->setLayout(new QVBoxLayout());
usbPage->layout()->addWidget(usbPageWidget);
setupConnections();
//load current drives
foreach(OptDevice device, QtEmuEnvironment::getHal()->opticalList())
cdImage->addItem(device.name, device.device);
//register all the widgets with their associated options
registerWidgets();
setupHelp();
disableUnsupportedOptions();
}
SettingsTab::~SettingsTab()
{
}
void SettingsTab::registerWidgets()
{
config->registerObject(cpuSpinBox, "cpu", QVariant(1));
config->registerObject(memorySpinBox, "memory");
config->registerObject(virtCheckBox, "virtualization", QVariant(false));
config->registerObject(hdImage, "hdd");
config->registerObject(cdImage, "cdrom");
config->registerObject(floppyImage, "floppy");
config->registerObject(cdBootCheck, "bootFromCd", QVariant(false));
config->registerObject(floppyBootCheck, "bootFromFloppy", QVariant(false));
config->registerObject(soundCheck, "sound", QVariant(false));
config->registerObject(soundCombo, "soundSystem", QVariant("oss"));
config->registerObject(timeCheck, "time", QVariant(true));
config->registerObject(embedCheck, "embeddedDisplay", QVariant(true));
config->registerObject(scaleCheck, "scaleEmbeddedDisplay", QVariant(true));
config->registerObject(portBox, "vncPort");
config->registerObject(hostEdit, "vncHost", QVariant("localhost"));
config->registerObject(tcpRadio, "vncTransport", QVariant("tcp"));
config->registerObject(fileRadio, "vncTransport");
config->registerObject(additionalCheck, "useAdditionalOptions", QVariant(false));
config->registerObject(additionalEdit, "additionalOptions");
config->registerObject(beforeCheck, "enableExecBefore", QVariant(false));
config->registerObject(beforeEdit, "execBefore");
config->registerObject(afterCheck, "enableExecAfter", QVariant(false));
config->registerObject(afterEdit, "execAfter");
config->registerObject(osCheck, "operatingSystem", QVariant("Other"));
config->registerObject(hiResCheck, "hiRes", QVariant(false));
config->registerObject(acpiCheck, "acpi", QVariant(true));
config->registerObject(hddAccelCheck, "hddVirtio", QVariant(false));
}
void SettingsTab::changeHelpTopic()
{
//QString helpFile = ;
QUrl helpFile(HelpWindow::getHelpLocation().toString() + "dynamic/" + settingsStack->currentWidget()->property("helpFile").toString());
helpView->load(helpFile);
}
void SettingsTab::setupHelp()
{
//set up the help browser
helpArea->hide();
changeHelpTopic();
connect(settingsStack, SIGNAL(currentChanged(int)), this, SLOT(changeHelpTopic()));
}
void SettingsTab::setupConnections()
{
connect(hdSelectButton, SIGNAL(clicked()), this, SLOT(setNewHddPath()));
connect(cdSelectButton, SIGNAL(clicked()), this, SLOT(setNewCdImagePath()));
connect(floppySelectButton, SIGNAL(clicked()), this, SLOT(setNewFloppyImagePath()));
connect(upgradeButton, SIGNAL(clicked()), this, SLOT(confirmUpgrade()));
//connections for usb support
UsbModel * model = usbPageWidget->getModel();\
UsbConfig * conf = parent->machineProcess->getUsbConfig();
connect(model, SIGNAL(vmDeviceAdded(QString)), conf, SLOT(vmAddDevice(QString)));
connect(model, SIGNAL(vmDeviceRemoved(QString)), conf, SLOT(vmRemoveDevice(QString)));
//connections for optical drive detection
connect(QtEmuEnvironment::getHal(), SIGNAL(opticalAdded(QString,QString)),this,SLOT(optAdded(QString,QString)));
connect(QtEmuEnvironment::getHal(), SIGNAL(opticalRemoved(QString,QString)),this,SLOT(optRemoved(QString,QString)));
}
//various file select dialogs
void SettingsTab::setNewHddPath()
{
QString newHddPath = QFileDialog::getOpenFileName(this, tr("Select a QtEmu hard disk image"),
config->getOption("hdd", myMachinesPath).toString(),
tr("QtEmu hard disk images")+" (*.img *.qcow *.vmdk *.hdd *.vpc)");
if (!newHddPath.isEmpty())
config->setOption("hdd", newHddPath);
}
void SettingsTab::setNewCdImagePath()
{
QString newCdPath = QFileDialog::getOpenFileName(this, tr("Select a CD Image"),
config->getOption("cdrom", myMachinesPath).toString(),
tr("CD ROM images")+" (*.iso *.img)");
if (!newCdPath.isEmpty())
config->setOption("cdrom", newCdPath);
}
void SettingsTab::setNewFloppyImagePath()
{
QString newFloppyPath = QFileDialog::getOpenFileName(this, tr("Select a Floppy Disk Image"),
config->getOption("floppy", myMachinesPath).toString(),
tr("Floppy disk images")+" (*.iso *.img)");
if (!newFloppyPath.isEmpty())
config->setOption("floppy", newFloppyPath);
}
//end file select dialogs
//warning dialogs
void SettingsTab::confirmUpgrade()
{
if (QMessageBox::question(this, tr("Upgrade Confirmation"),
tr("This will upgrade your Hard Disk image to the qcow format.<br />This enables more advanced features such as suspend/resume on all host operating systems and image compression on Windows hosts.<br />Your old image will remain intact, so if you want to revert afterwards you may do so."),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
== QMessageBox::Yes)
{
emit upgradeHdd();
}
}
//end warning dialogs
//load program wide settings
void SettingsTab::getSettings()
{
QSettings settings("QtEmu", "QtEmu");
myMachinesPath = settings.value("machinesPath", QString(QDir::homePath()+'/'+tr("MyMachines"))).toString();
}
void SettingsTab::setVirtSize(qint64 size)
{
QString sizeS;
float sizeK = size/1024.0;
float sizeM = sizeK/1024.0;
float sizeG = sizeM/1024.0;
if(sizeM<1)
sizeS = QString::number((int)sizeK) + "." + QString::number(((int)size)%1024) + " Kilobyte" + ((sizeK<2)?'\0':'s');
else if(sizeG<1)
sizeS = QString::number((int)sizeM) + "." + QString::number(((int)sizeK)%1024) + " Megabyte" + ((sizeM<2)?'\0':'s');
else
sizeS = QString::number((int)sizeG) + "." + QString::number(((int)sizeM)%1024) + " Gigabyte" + ((sizeG<2)?'\0':'s');
virtSizeLabel->setText(sizeS);
}
void SettingsTab::setPhySize(qint64 size)
{
QString sizeS;
float sizeK = size/1024.0;
float sizeM = sizeK/1024.0;
float sizeG = sizeM/1024.0;
if(sizeM<1)
sizeS = QString::number((int)sizeK) + "." + QString::number(((int)size)%1024) + " Kilobyte" + ((sizeK<2)?'\0':'s');
else if(sizeG<1)
sizeS = QString::number((int)sizeM) + "." + QString::number(((int)sizeK)%1024) + " Megabyte" + ((sizeM<2)?'\0':'s');
else
sizeS = QString::number((int)sizeG) + "." + QString::number(((int)sizeM)%1024) + " Gigabyte" + ((sizeG<2)?'\0':'s');
phySizeLabel->setText(sizeS);
}
void SettingsTab::getDrives()
{
//TODO:set a list of removable drives to be chosen by the dropdown menu for optical media / floppy drives. on linux this must be obtained through dbus, but on windows it can be gotten through Qt itself.
//qDebug(QDir::drives());
}
void SettingsTab::disableUnsupportedOptions()
{
if(QtEmuEnvironment::getKvmVersion()<1)
{
hddAccelCheck->setEnabled(false);
hddAccelCheck->setChecked(false);
// netPage->netAccelCheck->setEnabled(false);
// netPage->netAccelCheck->setChecked(false);
}
}
UsbPage* SettingsTab::getUsbPage()
{
return usbPageWidget;
}
void SettingsTab::optAdded(QString devName, QString devPath)
{
cdImage->addItem(devName, devPath);
}
void SettingsTab::optRemoved(QString devName, QString devPath)
{
cdImage->removeItem(cdImage->findData(devPath));
}
| 9,637
|
C++
|
.cpp
| 218
| 39.059633
| 320
| 0.68236
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,094
|
machinescrollarea.cpp
|
uwolfer_qtemu/machinescrollarea.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "machinescrollarea.h"
#include "vnc/vncview.h"
#include <QResizeEvent>
#include <QVariant>
//
MachineScrollArea::MachineScrollArea(QWidget* parent)
: QScrollArea(parent)
, splashShown(false)
{
setAlignment(Qt::AlignCenter);
setFrameShape(QFrame::NoFrame);
}
void MachineScrollArea::resizeEvent(QResizeEvent * event)
{
#ifdef DEVELOPER
qDebug("resized...");
#endif
resizeView(event->size().width(), event->size().height());
emit resized(event->size().width(), event->size().height());
QScrollArea::resizeEvent(event);
}
void MachineScrollArea::resizeView(int widgetWidth, int widgetHeight)
{
if(splashShown)
{
float aspectRatio = (1.0 * widget()->sizeHint().width()/ widget()->sizeHint().height());
int newWidth = (int)(widgetHeight*aspectRatio);
int newHeight = (int)(widgetWidth*(1/aspectRatio));
if(newWidth <= widgetWidth && newHeight > widgetHeight)
widget()->setFixedSize(newWidth, widgetHeight);
else
widget()->setFixedSize(widgetWidth, newHeight);
return;
}
widget()->blockSignals(true);
if(!property("scaleEmbeddedDisplay").toBool())
{
#ifdef DEVELOPER
qDebug("no scaling");
#endif
static_cast<VncView *>(widget())->enableScaling(false);
}
else
{
#ifdef DEVELOPER
qDebug("scaling");
#endif
static_cast<VncView *>(widget())->enableScaling(true);
static_cast<VncView *>(widget())->scaleResize(widgetWidth,widgetHeight);
}
widget()->blockSignals(false);
}
bool MachineScrollArea::isSplashShown()
{
return splashShown;
}
void MachineScrollArea::setSplashShown(bool value)
{
splashShown = value;
}
//
| 2,728
|
C++
|
.cpp
| 83
| 29.457831
| 96
| 0.668816
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,095
|
wizard.cpp
|
uwolfer_qtemu/wizard.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** Some parts of this file have been taken from
** examples/dialogs/complexwizard of Qt 4.1 which is
** Copyright (C) 2004-2006 Trolltech ASA. All rights reserved.
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "wizard.h"
#include <QPushButton>
#include <QFrame>
#include <QBoxLayout>
#include <QLabel>
#include <QSettings>
Wizard::Wizard(QWidget *parent)
: QDialog(parent)
{
cancelButton = new QPushButton(tr("Cancel"));
backButton = new QPushButton(tr("< &Back"));
nextButton = new QPushButton(tr("Next >"));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(backButton, SIGNAL(clicked()), this, SLOT(backButtonClicked()));
connect(nextButton, SIGNAL(clicked()), this, SLOT(nextButtonClicked()));
buttonLayout = new QHBoxLayout;
buttonLayout->addStretch(1);
buttonLayout->addWidget(cancelButton);
buttonLayout->addWidget(backButton);
buttonLayout->addWidget(nextButton);
headerFrame = new QFrame;
headerFrame->setFrameShape(QFrame::StyledPanel);
headerFrame->setFrameShadow(QFrame::Plain);
headerFrame->setAutoFillBackground(true);
headerFrame->setBackgroundRole(QPalette::Base);
QHBoxLayout *headerLayout = new QHBoxLayout;
headerLabel = new QLabel;
#if QT_VERSION >= 0x040200
headerLabel->setStyleSheet("QLabel { font-weight: bold; }");
#endif
headerLayout->addWidget(headerLabel);
QSettings settings("QtEmu", "QtEmu");
QString iconTheme = settings.value("iconTheme", "oxygen").toString();
headerIcon = new QLabel;
headerIcon->setPixmap(QPixmap(":/images/" + iconTheme + "/qtemu.png"));
headerLayout->addWidget(headerIcon);
headerLayout->setStretchFactor(headerLabel, 1);
headerFrame->setLayout(headerLayout);
mainLayout = new QVBoxLayout;
mainLayout->addWidget(headerFrame);
mainLayout->addLayout(buttonLayout);
setLayout(mainLayout);
}
void Wizard::setTitle(const QString &title)
{
headerLabel->setText(title);
}
void Wizard::setFirstPage(WizardPage *page)
{
page->resetPage();
history.append(page);
switchPage(0);
}
void Wizard::backButtonClicked()
{
WizardPage *oldPage = history.takeLast();
oldPage->resetPage();
switchPage(oldPage);
}
void Wizard::nextButtonClicked()
{
WizardPage *oldPage = history.last();
WizardPage *newPage = oldPage->nextPage();
newPage->resetPage();
history.append(newPage);
switchPage(oldPage);
}
void Wizard::completeStateChanged()
{
nextButton->setDefault(true);
WizardPage *currentPage = history.last();
nextButton->setEnabled(currentPage->isComplete());
if (currentPage->isLastPage())
nextButton->setText(tr("&Finish"));
else
nextButton->setText(tr("Next >"));
}
void Wizard::switchPage(WizardPage *oldPage)
{
if (oldPage)
{
oldPage->hide();
mainLayout->removeWidget(oldPage);
disconnect(oldPage, SIGNAL(completeStateChanged()),
this, SLOT(completeStateChanged()));
}
WizardPage *newPage = history.last();
mainLayout->insertWidget(1, newPage);
newPage->show();
newPage->setFocus();
newPage->updateTitle();
connect(newPage, SIGNAL(completeStateChanged()),
this, SLOT(completeStateChanged()));
backButton->setEnabled(history.size() != 1);
if (newPage->isLastPage())
{
disconnect(nextButton, SIGNAL(clicked()), this, SLOT(nextButtonClicked()));
connect(nextButton, SIGNAL(clicked()), this, SIGNAL(finished()));
connect(nextButton, SIGNAL(clicked()), this, SLOT(accept()));
}
else
{
disconnect(nextButton, SIGNAL(clicked()), this, SIGNAL(finished()));
disconnect(nextButton, SIGNAL(clicked()), this, SLOT(accept()));
disconnect(nextButton, SIGNAL(clicked()), this, SLOT(nextButtonClicked()));
connect(nextButton, SIGNAL(clicked()), this, SLOT(nextButtonClicked()));
}
completeStateChanged();
}
WizardPage::WizardPage(QWidget *parent)
: QWidget(parent)
{
hide();
}
void WizardPage::updateTitle()
{
}
void WizardPage::resetPage()
{
}
WizardPage *WizardPage::nextPage()
{
return 0;
}
bool WizardPage::isLastPage()
{
return false;
}
bool WizardPage::isComplete()
{
return true;
}
void WizardPage::privateSlot()
{
}
| 5,281
|
C++
|
.cpp
| 161
| 29.080745
| 83
| 0.691145
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,096
|
helpwindow.cpp
|
uwolfer_qtemu/helpwindow.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "helpwindow.h"
#include <QFile>
#include <QCoreApplication>
#include <QMessageBox>
#include <QSettings>
#include <QVBoxLayout>
#include <QTextBrowser>
#include <QTimer>
#include <QPushButton>
#include <QLocale>
HelpWindow::HelpWindow(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("QtEmu Help"));
resize(850, 600);
setSizeGripEnabled(true);
QTextBrowser *textBrowser = new QTextBrowser(this);
QUrl url = getHelpFile();
if (!url.isEmpty())
textBrowser->setSource(url);
else //there is no help available
QTimer::singleShot(0, this, SLOT(close()));
textBrowser->scroll(0, 0);
QPushButton *closeButton = new QPushButton(tr("Close"));
connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
QHBoxLayout *buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch(1);
buttonsLayout->addWidget(closeButton);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(textBrowser);
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
}
QUrl HelpWindow::getHelpFile()
{
QUrl url = QUrl(getHelpLocation().toString() + "main.htm");
if(url.isEmpty())
QMessageBox::critical(this, tr("Help not found"),
tr("Help not found. It is probably not installed."));
return url;
}
QUrl HelpWindow::getHelpLocation()
{
QSettings settings("QtEmu", "QtEmu");
QString locale = settings.value("language", QString(QLocale::system().name())).toString();
if (locale != "en")
{
//check for case when qtemu executable is in same dir (linux / win)
QUrl testUrl = QUrl(QCoreApplication::applicationDirPath() + "/help/" + locale);
if (QFile::exists(testUrl.toString()))
return testUrl;
//check for case when qtemu executable is in bin/ (installed on linux)
testUrl = QUrl(QCoreApplication::applicationDirPath() + "/../share/qtemu/help/" + locale);
if (QFile::exists(testUrl.toString()))
return testUrl;
}
//check for case when qtemu executable is in same dir (linux / win)
QUrl testUrl = QUrl(QCoreApplication::applicationDirPath() + "/help/");
if (QFile::exists(testUrl.toString()))
return testUrl;
//check for case when qtemu executable is in bin/ (installed on linux)
testUrl = QUrl(QCoreApplication::applicationDirPath() + "/../share/qtemu/help/");
if (QFile::exists(testUrl.toString()))
return testUrl;
//qDebug(testUrl.toString().toLocal8Bit().constData());
return QUrl();
}
| 3,584
|
C++
|
.cpp
| 89
| 36
| 98
| 0.668872
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,097
|
controlpanel.cpp
|
uwolfer_qtemu/controlpanel.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
/****************************************************************************
** C++ Implementation: controlpanel
**
** Description:
**
****************************************************************************/
#include "controlpanel.h"
#include "machineconfigobject.h"
#include "machinetab.h"
#include "machineprocess.h"
#include "settingstab.h"
#include "machineview.h"
#include "usbpage.h"
#include "usbmodel.h"
#include <QFileDialog>
#include <QStandardItemModel>
ControlPanel::ControlPanel(MachineTab *parent)
: QWidget(parent)
, parent(parent)
{
setupUi(this);
config = parent->machineConfigObject;
//load current drives
foreach(OptDevice device, QtEmuEnvironment::getHal()->opticalList())
cdCombo->addItem(device.name, device.device);
registerObjects();
makeConnections();
QPalette listPalette = usbView->palette();
QColor transparent = QColor();
transparent.setAlpha(0);
listPalette.setColor(QPalette::Base, transparent);
usbView->setPalette(listPalette);
}
ControlPanel::~ControlPanel()
{
}
void ControlPanel::makeConnections()
{
//navigation connections
connect(mediaButton, SIGNAL(clicked()), this, SLOT(mediaActivate()));
//connect(optionButton, SIGNAL(clicked()), this, SLOT(optionActivate()));
connect(displayButton, SIGNAL(clicked()), this, SLOT(displayActivate()));
connect(usbButton, SIGNAL(clicked()), this, SLOT(usbActivate()));
//action connections
connect(cdReloadButton, SIGNAL(clicked()), parent->machineProcess, SLOT(changeCdrom()));
connect(floppyReloadButton, SIGNAL(clicked()), parent->machineProcess, SLOT(changeFloppy()));
connect(cdImageButton, SIGNAL(clicked()), parent->settingsTab, SLOT(setNewCdImagePath()));
connect(floppyImageButton, SIGNAL(clicked()), parent->settingsTab, SLOT(setNewFloppyImagePath()));
connect(fullscreenButton, SIGNAL(toggled(bool)), parent->machineView, SLOT(fullscreen(bool)));
connect(parent->machineView, SIGNAL(fullscreenToggled(bool)), fullscreenButton, SLOT(setChecked(bool)));
connect(screenshotButton, SIGNAL(clicked()), this, SLOT(saveScreenshot()));
//state connections
connect(parent->machineProcess, SIGNAL(started()), this, SLOT(running()));
connect(parent->machineProcess, SIGNAL(finished()), this, SLOT(stopped()));
//connections for optical drive detection
connect(QtEmuEnvironment::getHal(), SIGNAL(opticalAdded(QString,QString)),this,SLOT(optAdded(QString,QString)));
connect(QtEmuEnvironment::getHal(), SIGNAL(opticalRemoved(QString,QString)),this,SLOT(optRemoved(QString,QString)));
}
void ControlPanel::mediaActivate()
{
controlStack->setCurrentIndex(0);
}
void ControlPanel::displayActivate()
{
controlStack->setCurrentIndex(2);
}
void ControlPanel::usbActivate()
{
controlStack->setCurrentIndex(1);
}
void ControlPanel::registerObjects()
{
config->registerObject(cdCombo, "cdrom");
config->registerObject(floppyCombo, "floppy");
config->registerObject(mouseButton, "mouse");
config->registerObject(scaleButton, "scaleEmbeddedDisplay");
config->registerObject(addDevices, "autoAddDevices");
usbFrame->setProperty("enableDisable", true);
config->registerObject(usbFrame, "usbSupport");
//connect the usb view to the model.
usbView->setModel(parent->settingsTab->getUsbPage()->getModel());
}
void ControlPanel::saveScreenshot()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save a Screenshot"),
QString(),
tr("Pictures")+" (*.ppm)");
if(!fileName.endsWith(".ppm"))
fileName = fileName + ".ppm";
parent->machineProcess->write(QString("screendump " + fileName).toAscii() + '\n');
}
void ControlPanel::running()
{
fullscreenButton->setEnabled(true);
screenshotButton->setEnabled(true);
}
void ControlPanel::stopped()
{
fullscreenButton->setEnabled(false);
screenshotButton->setEnabled(false);
}
void ControlPanel::optionChanged(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value)
{
if(optionName == "autoAddDevices")
{
usbView->setEnabled(config->getOption("autoAddDevices", true).toBool());
}
}
void ControlPanel::optAdded(QString devName, QString devPath)
{
cdCombo->addItem(devName, devPath);
}
void ControlPanel::optRemoved(QString devName, QString devPath)
{
if(cdCombo->itemData(cdCombo->currentIndex()).toString() == devPath)
{
parent->machineProcess->changeCdrom();
}
cdCombo->removeItem(cdCombo->findData(devPath));
}
| 5,677
|
C++
|
.cpp
| 142
| 36.183099
| 132
| 0.690394
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,098
|
usbpage.cpp
|
uwolfer_qtemu/usbpage.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "usbpage.h"
#include "machineconfigobject.h"
#include "usbmodel.h"
#include "settingstab.h"
UsbPage::UsbPage(MachineConfigObject *config, QWidget *parent)
: QWidget(parent)
, config(config)
{
setupUi(this);
model = new UsbModel(config, this);
registerWidgets();
}
UsbPage::~UsbPage()
{
}
void UsbPage::registerWidgets()
{
config->registerObject(mouseCheck, "mouse", QVariant(true));
config->registerObject(usbCheck, "usbSupport", QVariant(true));
config->registerObject(addCheck, "autoAddDevices", QVariant(false));
config->registerObject(model, "autoAddDevices", QVariant(false));
usbView->setModel(model);
}
UsbModel* UsbPage::getModel()
{
return model;
}
| 1,724
|
C++
|
.cpp
| 49
| 33.285714
| 77
| 0.682445
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,099
|
configwindow.cpp
|
uwolfer_qtemu/configwindow.cpp
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "configwindow.h"
#include "config.h"
#include <QTextEdit>
#include <QComboBox>
#include <QSettings>
#include <QBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QGroupBox>
#include <QCheckBox>
#include <QFileDialog>
#include <QCoreApplication>
ConfigWindow::ConfigWindow(const QString &myMachinesPathParent, int tabPosition, QWidget *parent)
: QDialog((QWidget*)parent)
{
myMachinesPath = myMachinesPathParent;
setWindowTitle(tr("QtEmu Config"));
resize(400, 200);
setSizeGripEnabled(true);
QGroupBox *generalGroupBox = new QGroupBox(tr("General"), this);
QLabel *myMachinesPathLabel = new QLabel(tr("Default \"MyMachines\" Path:"));
myMachinePathLineEdit = new QLineEdit(myMachinesPath);
myMachinesPathLabel->setBuddy(myMachinePathLineEdit);
QSettings settings("QtEmu", "QtEmu");
QString iconTheme = settings.value("iconTheme", "oxygen").toString();
QPushButton *pathSelectButton = new QPushButton(QIcon(":/images/" + iconTheme + "/open.png"), QString());
connect(pathSelectButton, SIGNAL(clicked()), this, SLOT(setNewPath()));
QHBoxLayout *pathLayout = new QHBoxLayout;
pathLayout->addWidget(myMachinePathLineEdit);
pathLayout->addWidget(pathSelectButton);
QLabel *tabPositionLabel = new QLabel(tr("Tabbar position:"));
comboTabPosition = new QComboBox;
comboTabPosition->addItem(tr("Top"));
comboTabPosition->addItem(tr("Bottom"));
comboTabPosition->addItem(tr("Left"));
comboTabPosition->addItem(tr("Right"));
comboTabPosition->setCurrentIndex(tabPosition);
tabPositionLabel->setBuddy(comboTabPosition);
QLabel *iconThemeLabel = new QLabel(tr("Icon theme (*):"));
comboIconTheme = new QComboBox;
comboIconTheme->addItem("Oxygen");
comboIconTheme->addItem("Crystal");
comboIconTheme->setCurrentIndex(tabPosition);
iconThemeLabel->setBuddy(comboIconTheme);
QLabel *languageLabel = new QLabel(tr("Language (*):"));
languagePosition = new QComboBox; //make the language name not tranlatable (no tr()!) and write them translated
languagePosition->addItem("English");
languagePosition->addItem("Deutsch");
languagePosition->addItem(QString::fromUtf8("Türkçe"));
languagePosition->addItem(QString::fromUtf8("Русский"));
languagePosition->addItem(QString::fromUtf8("Česky"));
languagePosition->addItem(QString::fromUtf8("Español"));
languagePosition->addItem(QString::fromUtf8("Français"));
languagePosition->addItem(QString::fromUtf8("Italiano"));
languagePosition->addItem(QString::fromUtf8("Português do Brasil"));
languagePosition->addItem(QString::fromUtf8("Polski"));
QString language = settings.value("language", QString(QLocale::system().name())).toString();
int index;
if (language == "en")
index = 0;
else if (language == "de")
index = 1;
else if (language == "tr")
index = 2;
else if (language == "ru")
index = 3;
else if (language == "cz")
index = 4;
else if (language == "es")
index = 5;
else if (language == "fr")
index = 6;
else if (language == "it")
index = 7;
else if (language == "pt-BR")
index = 8;
else if (language == "pl")
index = 9;
else
index = 0;
languagePosition->setCurrentIndex(index);
connect(languagePosition, SIGNAL(currentIndexChanged(int)), this, SLOT(languageChange(int)));
languageLabel->setBuddy(languagePosition);
QLabel *restartLabel = new QLabel(tr("<i>(*) Change requires restart of QtEmu.</i>"));
QGridLayout *generalLayout = new QGridLayout;
generalLayout->addWidget(myMachinesPathLabel, 1, 0);
generalLayout->addLayout(pathLayout, 1, 1);
generalLayout->addWidget(tabPositionLabel, 2, 0);
generalLayout->addWidget(comboTabPosition, 2, 1);
generalLayout->addWidget(iconThemeLabel, 3, 0);
generalLayout->addWidget(comboIconTheme, 3, 1);
generalLayout->addWidget(languageLabel, 4, 0);
generalLayout->addWidget(languagePosition, 4, 1);
generalLayout->addWidget(restartLabel, 5, 0);
generalGroupBox->setLayout(generalLayout);
QGroupBox *qemuGroupBox = new QGroupBox(tr("Start and stop QEMU"), this);
QLabel *beforeStartExeLabel = new QLabel(tr("Execute before start:"));
beforeStartExeTextEdit = new QTextEdit;
beforeStartExeLabel->setBuddy(beforeStartExeTextEdit);
QLabel *commandLabel = new QLabel(tr("QEMU start command:"));
commandLineEdit = new QLineEdit;
commandLabel->setBuddy(commandLineEdit);
QLabel *afterExitExeLabel = new QLabel(tr("Execute after exit:"));
afterExitExeTextEdit = new QTextEdit;
afterExitExeLabel->setBuddy(afterExitExeTextEdit);
QGridLayout *qemuLayout = new QGridLayout;
qemuLayout->addWidget(beforeStartExeLabel, 1, 0, Qt::AlignTop);
qemuLayout->addWidget(beforeStartExeTextEdit, 1, 1);
qemuLayout->addWidget(commandLabel, 2, 0);
qemuLayout->addWidget(commandLineEdit, 2, 1);
qemuLayout->addWidget(afterExitExeLabel, 4, 0, Qt::AlignTop);
qemuLayout->addWidget(afterExitExeTextEdit, 4, 1);
qemuLayout->setRowStretch(4, 1);
qemuGroupBox->setLayout(qemuLayout);
QPushButton *okButton = new QPushButton(tr("OK"));
connect(okButton, SIGNAL(clicked()), this, SLOT(writeSettings()));
QPushButton *cancelButton = new QPushButton(tr("Cancel"));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
QHBoxLayout *buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch(1);
buttonsLayout->addWidget(okButton);
buttonsLayout->addWidget(cancelButton);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(generalGroupBox);
mainLayout->addWidget(qemuGroupBox);
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
loadSettings();
}
void ConfigWindow::setNewPath()
{
QString newPath = QFileDialog::getExistingDirectory(this, tr("Select a folder for \"MyMachines\""),
myMachinesPath);
if (!newPath.isEmpty())
myMachinePathLineEdit->setText(newPath);
}
void ConfigWindow::languageChange(int index)
{
QSettings settings("QtEmu", "QtEmu");
QString languageString;
switch(index)
{
case 0: languageString = "en";
break;
case 1: languageString = "de";
break;
case 2: languageString = "tr";
break;
case 3: languageString = "ru";
break;
case 4: languageString = "cz";
break;
case 5: languageString = "es";
break;
case 6: languageString = "fr";
break;
case 7: languageString = "it";
break;
case 8: languageString = "pt-BR";
break;
case 9: languageString = "pl";
break;
default: languageString = "en";
}
settings.setValue("language", languageString);
}
void ConfigWindow::loadSettings()
{
QSettings settings("QtEmu", "QtEmu");
beforeStartExeTextEdit->setPlainText(settings.value("beforeStart").toString());
#ifndef Q_OS_WIN32
commandLineEdit->setText(settings.value("command", "qemu").toString());
#elif defined(Q_OS_WIN32)
commandLineEdit->setText(settings.value("command", QCoreApplication::applicationDirPath() + "/qemu/qemu.exe").toString());
#endif
afterExitExeTextEdit->setPlainText(settings.value("afterExit").toString());
comboIconTheme->setCurrentIndex(comboIconTheme->findText(settings.value("iconTheme", "oxygen").toString(), Qt::MatchContains));
}
void ConfigWindow::writeSettings()
{
QSettings settings("QtEmu", "QtEmu");
settings.setValue("beforeStart", beforeStartExeTextEdit->toPlainText());
settings.setValue("command", commandLineEdit->text());
settings.setValue("afterExit", afterExitExeTextEdit->toPlainText());
settings.setValue("iconTheme", comboIconTheme->currentText().toLower());
accept();
}
| 9,038
|
C++
|
.cpp
| 210
| 37.766667
| 131
| 0.694745
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,100
|
halobject.cpp
|
uwolfer_qtemu/halobject.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "halobject.h"
#include <QDebug>
/***************************************************************************
**
** HalObject is supposed to be used ONCE by qtemu, and each VM talks to it.
** HalObject or another class should assure that only one machine uses each
** device, but this is not done yet.
**
***************************************************************************/
HalObject::HalObject()
{
hal = new QDBusInterface("org.freedesktop.Hal",
"/org/freedesktop/Hal/Manager",
"org.freedesktop.Hal.Manager",
QDBusConnection::systemBus(),
this);
connect(hal, SIGNAL(DeviceAdded(QString)), this, SLOT(halDeviceAdded(QString)));
connect(hal, SIGNAL(DeviceRemoved(QString)), this, SLOT(halDeviceRemoved(QString)));
QDBusReply<QStringList> deviceList = hal->call("GetAllDevices");
if (deviceList.isValid())
{
for(int i = 0; i < deviceList.value().size(); i++)
halDeviceAdded(deviceList.value().at(i));
}
else
{
//hal is probably not installed or running
}
}
void HalObject::halDeviceAdded(QString name)
{
QDBusInterface * tempInterface = new QDBusInterface("org.freedesktop.Hal",
name,
"org.freedesktop.Hal.Device",
QDBusConnection::systemBus(),
this);
//generic device signal
emit deviceAdded(name);
#ifdef DEVELOPER
qDebug(name.toAscii());
qDebug("capabilities:" + QVariant(tempInterface->call("GetPropertyStringList", "info.capabilities").arguments()).toStringList().join(", ").toAscii());
#endif
//USB device that is not a hub added...
if(tempInterface->call("GetProperty", "info.subsystem").arguments().at(0).toString() == "usb_device" &&
tempInterface->call("GetProperty", "usb_device.num_ports").arguments().at(0).toInt() == 0 )
{
#ifdef DEVELOPER
qDebug("usb added");
#endif
UsbDevice device;
device.address = tempInterface->call("GetProperty", "usb_device.bus_number").arguments().at(0).toString() + '.' +
tempInterface->call("GetProperty", "usb_device.linux.device_number").arguments().at(0).toString();
device.id = name;
device.product = tempInterface->call("GetProperty", "info.product").arguments().at(0).toString();
device.vendor = tempInterface->call("GetProperty", "info.vendor").arguments().at(0).toString();
usbDeviceHash.insert(name, device);
emit usbAdded(name, device);
}
else if(tempInterface->call("QueryCapability", "storage.cdrom").arguments().at(0).toBool())
{
#ifdef DEVELOPER
qDebug("optical added");
qDebug("at device: " + tempInterface->call("GetProperty", "block.device").arguments().at(0).toByteArray());
#endif
OptDevice device;
device.device = tempInterface->call("GetProperty", "block.device").arguments().at(0).toString();
device.id = name;
device.name = tempInterface->call("GetProperty", "storage.model").arguments().at(0).toString();
optDeviceHash.insert(name, device);
emit opticalAdded(device.name, device.device);
}
else if(tempInterface->call("QueryCapability", "volume.disc").arguments().at(0).toBool())
{
foreach(OptDevice testDevice, optDeviceHash)
{
if(testDevice.device == tempInterface->call("GetProperty", "block.device").arguments().at(0).toString())
{
testDevice.volume = tempInterface->call("GetProperty", "volume.label").arguments().at(0).toString();
testDevice.volumeId = name;
emit opticalAdded(testDevice.name + " (" + testDevice.volume + ')', testDevice.device);
emit opticalRemoved(testDevice.name, testDevice.device);
optDeviceHash.insert(testDevice.id, testDevice);
break;
}
}
}
}
void HalObject::halDeviceRemoved(QString name)
{
//generic device signal
emit(deviceRemoved(name));
#ifdef DEVELOPER
qDebug(name.toAscii());
#endif
//USB device that is not a hub deleted...
if(usbDeviceHash.contains(name))
{
#ifdef DEVELOPER
qDebug("usb removed");
#endif
emit usbRemoved(name, usbDeviceHash.value(name));
usbDeviceHash.remove(name);
}
if(optDeviceHash.contains(name))
{
#ifdef DEVELOPER
qDebug("optical removed");
#endif
emit opticalRemoved(optDeviceHash.value(name).name, optDeviceHash.value(name).device);
optDeviceHash.remove(name);
}
foreach(OptDevice testDevice, optDeviceHash)
{
if(testDevice.volumeId == name)
{
emit opticalAdded(testDevice.name, testDevice.device);
emit opticalRemoved(testDevice.name + " (" + testDevice.volume + ')', testDevice.device);
testDevice.volume.clear();
testDevice.volumeId.clear();
optDeviceHash.insert(testDevice.id, testDevice);
break;
}
}
}
const QList<UsbDevice> HalObject::usbList()
{
return usbDeviceHash.values();
}
const QList<OptDevice> HalObject::opticalList()
{
return optDeviceHash.values();
}
| 6,458
|
C++
|
.cpp
| 154
| 34.253247
| 154
| 0.606745
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,101
|
qtemuenvironment.cpp
|
uwolfer_qtemu/qtemuenvironment.cpp
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#include "halobject.h"
#include "qtemuenvironment.h"
#include <QSettings>
#include <QProcess>
#include <QDir>
#include <QString>
QtEmuEnvironment::QtEmuEnvironment()
{
getVersion();
if(hal == 0)
hal = new HalObject();
}
QtEmuEnvironment::~ QtEmuEnvironment()
{
}
void QtEmuEnvironment::getVersion()
{
QSettings settings("QtEmu", "QtEmu");
QString versionString;
QProcess *findVersion = new QProcess();
#ifndef Q_OS_WIN32
const QString qemuCommand = settings.value("command", "qemu").toString();
#elif defined(Q_OS_WIN32)
const QString qemuCommand = settings.value("command", QCoreApplication::applicationDirPath() + "/qemu/qemu.exe").toString();
QDir path(qemuCommand);
path.cdUp();
setWorkingDirectory(path->path());
#endif
findVersion->start(qemuCommand, QStringList("--help"));
findVersion->waitForFinished();
if( findVersion->error() != QProcess::UnknownError )
{
qemuVersion[0] = -1;
qemuVersion[1] = -1;
qemuVersion[2] = -1;
kvmVersion = -1;
return;
}
QString infoString = findVersion->readLine();
if( !infoString.contains("QEMU") )
{
qemuVersion[0] = -1;
qemuVersion[1] = -1;
qemuVersion[2] = -1;
kvmVersion = -1;
return;
}
QStringList infoStringList = infoString.split(' ');
versionString = infoStringList.at(4);
QStringList versionStringList = versionString.split('.');
qemuVersion[0] = versionStringList.at(0).toInt();
qemuVersion[1] = versionStringList.at(1).toInt();
qemuVersion[2] = versionStringList.at(2).toInt();
versionString = infoStringList.at(5);
if(versionString.contains(QRegExp("kvm")))
{
kvmVersion = versionString.remove(QRegExp("\\D")).toInt();
if(kvmVersion == 0)
kvmVersion = -1; //indicates we think we've got kvm, but can't figure out what version
}
else
kvmVersion = 0; //must be QEMU
//grab the rest of the help text and search for kvm and kqemu options...
QString helpString = findVersion->readAll();
if(helpString.contains("kqemu"))
supportsKqemu = true;
else
supportsKqemu = false;
if(helpString.contains("kvm"))
supportsKvm = true;
else
supportsKvm = false;
delete findVersion;
#ifdef Q_OS_WIN32
delete path;
#endif
versionChecked = true;
#ifdef DEVELOPER
qDebug(("kvm: " + QString::number(kvmVersion) + " qemu: " + QString::number(qemuVersion[0]) + '.' + QString::number(qemuVersion[1]) + '.' + QString::number(qemuVersion[2])).toAscii());
#endif
}
int * QtEmuEnvironment::getQemuVersion()
{
if(!versionChecked)
getVersion();
return qemuVersion;
}
int QtEmuEnvironment::getKvmVersion()
{
if(!versionChecked)
getVersion();
return kvmVersion;
}
HalObject* QtEmuEnvironment::getHal()
{
if(hal == 0)
hal = new HalObject();
return hal;
}
bool QtEmuEnvironment::kvmSupport()
{
if(!versionChecked)
getVersion();
return supportsKvm;
}
bool QtEmuEnvironment::kqemuSupport()
{
if(!versionChecked)
getVersion();
return supportsKqemu;
}
HalObject* QtEmuEnvironment::hal = 0;
int QtEmuEnvironment::qemuVersion[] = {-1, -1, -1};
int QtEmuEnvironment::kvmVersion = -1;
bool QtEmuEnvironment::versionChecked = false;
bool QtEmuEnvironment::supportsKvm = false;
bool QtEmuEnvironment::supportsKqemu = false;
| 4,490
|
C++
|
.cpp
| 139
| 28.079137
| 188
| 0.664195
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,103
|
guesttools.cpp
|
uwolfer_qtemu/GuestTools/guesttools.cpp
|
#include "guesttools.h"
#include "modules/clipboard/clipboardsync.h"
//#include <qextserialport.h>
//#include <QDataStream>
#include <QMenu>
#include <QIcon>
#include <QDebug>
#include <QMessageBox>
#include <QIODevice>
GuestTools::GuestTools(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
blockSize = 0;
initSerialPort();
createActions();
createTrayIcon();
createModules();
connect(port, SIGNAL(readyRead()), this, SLOT(ioReceived()));
trayIcon->show();
}
GuestTools::~GuestTools()
{
}
void GuestTools::createTrayIcon()
{
trayIconMenu = new QMenu(this);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon(":/guestTray.png"));
setWindowIcon(QIcon(":/guestTray.png"));
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(clickedIcon(QSystemTrayIcon::ActivationReason)));
}
void GuestTools::createActions()
{
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void GuestTools::clickedIcon(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick)
{
if(this->isVisible())
this->hide();
else
this->show();
}
}
void GuestTools::ioReceived()
{
//connect the stream
QDataStream stream(port);
stream.setVersion(QDataStream::Qt_4_0);
//get the size of the data chunk
if (blockSize == 0) {
if (port->bytesAvailable() < (int)sizeof(quint64))
return;
stream >> blockSize;
}
//don't continue until we have all the data
if ((quint64)(port->bytesAvailable()) < blockSize)
return;
QString usesModule;
QVariant data;
stream >> usesModule >> data;
blockSize = 0;
for(int i = 0; i < modules.size(); i++)
{
if(modules.at(i)->moduleName() == usesModule)
{
qDebug() << "received data from"<< usesModule;
modules.at(i)->receiveData(data);
return;
}
}
qDebug() << "invalid module" << usesModule;
}
void GuestTools::createModules()
{
modules.append(new ClipboardSync(this));
}
void GuestTools::dataSender(QString module, QVariant &data)
{
//so that we don't try to send more than one at a time
//sender()->blockSignals(true);
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint64)0;
out << module;
out << data;
out.device()->seek(0);
out << (quint64)(block.size() - sizeof(quint64));
port->write(block);
//re-allow signals
//sender()->blockSignals(false);
}
void GuestTools::initSerialPort()
{
#ifdef Q_WS_WIN
port = new QextSerialPort("COM1", QextSerialPort::EventDriven);
#else
port = new QextSerialPort("ttyS0", QextSerialPort::EventDriven);
#endif
port->setBaudRate(BAUD115200);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
port->open(QIODevice::ReadWrite);
if (!(port->lineStatus() & LS_DSR)) {
qDebug() << "warning: QtEmu not listening";
}
}
| 3,330
|
C++
|
.cpp
| 116
| 23.991379
| 136
| 0.665094
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,104
|
guestmodule.cpp
|
uwolfer_qtemu/GuestTools/modules/guestmodule.cpp
|
/*
* guestmodule.cpp
*
* Created on: Dec 14, 2008
* Author: Ben
*/
#include "guestmodule.h"
#include <QDebug>
GuestModule::GuestModule(QObject *parent)
: QObject(parent)
{
connect(this, SIGNAL(sendData(QString, QVariant&)), parent, SLOT(dataSender(QString, QVariant&)));
}
GuestModule::~GuestModule() {
}
QString GuestModule::moduleName()
{
return module;
}
void GuestModule::setModuleName(QString name)
{
module = name;
}
void GuestModule::receiveData(QVariant data)
{
}
void GuestModule::send(QVariant &data)
{
emit sendData(module, data);
}
| 580
|
C++
|
.cpp
| 30
| 17.333333
| 102
| 0.734317
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,105
|
clipboardsync.cpp
|
uwolfer_qtemu/GuestTools/modules/clipboard/clipboardsync.cpp
|
#include "clipboardsync.h"
#include <QApplication>
#include <QClipboard>
#include <QImage>
#include <QString>
#include <QDebug>
ClipboardSync::ClipboardSync(QObject *parent)
: GuestModule(parent)
{
previous = QVariant();
setModuleName("clipboard");
clipboard = QApplication::clipboard();
clipboard->clear(QClipboard::Clipboard);
clipboard->clear(QClipboard::Selection);
connect(clipboard, SIGNAL(changed(QClipboard::Mode)), this, SLOT(dataChanged(QClipboard::Mode)));
qDebug() << "clipboard initialized";
}
ClipboardSync::~ClipboardSync()
{
}
void ClipboardSync::receiveData(QVariant data)
{
qDebug() << "received clipboard data";
QVariant::Type type = data.type();
if(type == QVariant::Image)
{
QImage image = data.value<QImage>();
clipboard->setImage(image, QClipboard::Clipboard);
clipboard->setImage(image, QClipboard::Selection);
previous = data;
}
else if(type == QVariant::String)
{
QString text = data.value<QString>();
clipboard->setText(text, QClipboard::Clipboard);
clipboard->setText(text, QClipboard::Selection);
previous = data;
}
else
qDebug() << "unknown data format!";
}
void ClipboardSync::dataChanged(QClipboard::Mode mode)
{
if(!clipboard->image(mode).isNull())
{
if(previous == QVariant(clipboard->image(mode)))
return;
previous = QVariant(clipboard->image(mode));
send(previous);
}
else if(!clipboard->text(mode).isNull())
{
if(previous == QVariant(clipboard->text(mode)))
return;
previous = QVariant(clipboard->text(mode));
qDebug() << previous;
send(previous);
}
else
qDebug() << "got clipboard data, but can't find an image or text!";
}
| 1,762
|
C++
|
.cpp
| 61
| 24.606557
| 101
| 0.680047
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
754,106
|
clipboardpoll.cpp
|
uwolfer_qtemu/GuestTools/modules/clipboard/clipboardpoll.cpp
|
// -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 8; -*-
/* This file is part of the KDE project
Copyright (C) 2003 by Lubos Lunak <l.lunak@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <config-workspace.h>
#include <config-X11.h>
#include "clipboardpoll.h"
#include <kapplication.h>
#include <QClipboard>
#include <kdebug.h>
#include <X11/Xatom.h>
#include <time.h>
#include <QX11Info>
#ifdef HAVE_XFIXES
#include <X11/extensions/Xfixes.h>
#endif
#include "klipper.h"
//#define NOISY_KLIPPER_
/*
The polling magic:
There's no way with X11 how to find out if the selection has changed (unless its ownership
is taken away from the current client). In the future, there will be hopefully such notification,
which will make this whole file more or less obsolete. But for now, Klipper has to poll.
In order to avoid transferring all the data on every time pulse, this file implements two
optimizations: The first one is checking whether the selection owner is Qt application (using
the _QT_SELECTION/CLIPBOARD_SENTINEL atoms on the root window of screen 0), and if yes,
Klipper can rely on QClipboard's signals. If the owner is not Qt app, and the ownership has changed,
it means the selection has changed as well. Otherwise, first only the timestamp
of the last selection change is requested using the TIMESTAMP selection target, and if it's
the same, it's assumed the contents haven't changed. Note that some applications (like XEmacs) does
not provide this information, so Klipper has to assume that the clipboard might have changed in this
case --- this is what is meant by REFUSED below.
Update: Now there's also support for XFixes, so in case XFixes support is detected, only XFixes is
used for detecting changes, everything else is ignored, even Qt's clipboard signals.
*/
ClipboardPoll::ClipboardPoll()
: m_xfixes_event_base( -1 )
{
hide();
const char* names[ 6 ]
= { "_QT_SELECTION_SENTINEL",
"_QT_CLIPBOARD_SENTINEL",
"CLIPBOARD",
"TIMESTAMP",
"KLIPPER_SELECTION_TIMESTAMP",
"KLIPPER_CLIPBOARD_TIMESTAMP" };
Atom atoms[ 6 ];
XInternAtoms( QX11Info::display(), const_cast< char** >( names ), 6, False, atoms );
m_selection.sentinel_atom = atoms[ 0 ];
m_clipboard.sentinel_atom = atoms[ 1 ];
m_xa_clipboard = atoms[ 2 ];
m_xa_timestamp = atoms[ 3 ];
m_selection.timestamp_atom = atoms[ 4 ];
m_clipboard.timestamp_atom = atoms[ 5 ];
bool use_polling = true;
kapp->installX11EventFilter( this );
m_timer.setSingleShot( false );
#ifdef HAVE_XFIXES
int dummy;
if( XFixesQueryExtension( QX11Info::display(), &m_xfixes_event_base, &dummy ))
{
XFixesSelectSelectionInput( QX11Info::display(), QX11Info::appRootWindow( 0 ), XA_PRIMARY,
XFixesSetSelectionOwnerNotifyMask |
XFixesSelectionWindowDestroyNotifyMask |
XFixesSelectionClientCloseNotifyMask );
XFixesSelectSelectionInput( QX11Info::display(), QX11Info::appRootWindow( 0 ), m_xa_clipboard,
XFixesSetSelectionOwnerNotifyMask |
XFixesSelectionWindowDestroyNotifyMask |
XFixesSelectionClientCloseNotifyMask );
use_polling = false;
#ifdef NOISY_KLIPPER_
kDebug() << "Using XFIXES";
#endif
}
#endif
if( use_polling )
{
#ifdef NOISY_KLIPPER_
kDebug() << "Using polling";
#endif
initPolling();
}
}
void ClipboardPoll::initPolling()
{
connect( kapp->clipboard(), SIGNAL( selectionChanged() ), SLOT(qtSelectionChanged()));
connect( kapp->clipboard(), SIGNAL( dataChanged() ), SLOT( qtClipboardChanged() ));
connect( &m_timer, SIGNAL( timeout()), SLOT( timeout()));
m_timer.start( 1000 );
m_selection.atom = XA_PRIMARY;
m_clipboard.atom = m_xa_clipboard;
m_selection.last_change = m_clipboard.last_change = QX11Info::appTime(); // don't trigger right after startup
m_selection.last_owner = XGetSelectionOwner( QX11Info::display(), XA_PRIMARY );
#ifdef NOISY_KLIPPER_
kDebug() << "(1) Setting last_owner for =" << "selection" << ":" << m_selection.last_owner;
#endif
m_clipboard.last_owner = XGetSelectionOwner( QX11Info::display(), m_xa_clipboard );
#ifdef NOISY_KLIPPER_
kDebug() << "(2) Setting last_owner for =" << "clipboard" << ":" << m_clipboard.last_owner;
#endif
m_selection.waiting_for_timestamp = false;
m_clipboard.waiting_for_timestamp = false;
updateQtOwnership( m_selection );
updateQtOwnership( m_clipboard );
}
void ClipboardPoll::qtSelectionChanged()
{
emit clipboardChanged( true );
}
void ClipboardPoll::qtClipboardChanged()
{
emit clipboardChanged( false );
}
bool ClipboardPoll::x11Event( XEvent* e )
{
// note that this is also installed as app-wide filter
#ifdef HAVE_XFIXES
if( m_xfixes_event_base != -1 && e->type == m_xfixes_event_base + XFixesSelectionNotify )
{
XFixesSelectionNotifyEvent* ev = reinterpret_cast< XFixesSelectionNotifyEvent* >( e );
if( ev->selection == XA_PRIMARY && !kapp->clipboard()->ownsSelection())
{
#ifdef NOISY_KLIPPER_
kDebug() << "SELECTION CHANGED (XFIXES)";
#endif
QX11Info::setAppTime( ev->timestamp );
emit clipboardChanged( true );
}
else if( ev->selection == m_xa_clipboard && !kapp->clipboard()->ownsClipboard())
{
#ifdef NOISY_KLIPPER_
kDebug() << "CLIPBOARD CHANGED (XFIXES)";
#endif
QX11Info::setAppTime( ev->timestamp );
emit clipboardChanged( false );
}
}
#endif
if( e->type == SelectionNotify && e->xselection.requestor == winId())
{
if( changedTimestamp( m_selection, *e ) ) {
#ifdef NOISY_KLIPPER_
kDebug() << "SELECTION CHANGED (GOT TIMESTAMP)";
#endif
emit clipboardChanged( true );
}
if ( changedTimestamp( m_clipboard, *e ) )
{
#ifdef NOISY_KLIPPER_
kDebug() << "CLIPBOARD CHANGED (GOT TIMESTAMP)";
#endif
emit clipboardChanged( false );
}
return true; // filter out
}
return false;
}
void ClipboardPoll::updateQtOwnership( SelectionData& data )
{
Atom type;
int format;
unsigned long nitems;
unsigned long after;
unsigned char* prop = NULL;
if( XGetWindowProperty( QX11Info::display(), QX11Info::appRootWindow( 0 ), data.sentinel_atom, 0, 2, False,
XA_WINDOW, &type, &format, &nitems, &after, &prop ) != Success
|| type != XA_WINDOW || format != 32 || nitems != 2 || prop == NULL )
{
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "UPDATEQT BAD PROPERTY";
#endif
data.owner_is_qt = false;
if( prop != NULL )
XFree( prop );
return;
}
Window owner = reinterpret_cast< long* >( prop )[ 0 ]; // [0] is new owner, [1] is previous
XFree( prop );
Window current_owner = XGetSelectionOwner( QX11Info::display(), data.atom );
data.owner_is_qt = ( owner == current_owner );
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "owner=" << owner << "; current_owner=" << current_owner;
kDebug() << "UPDATEQT:" << ( &data == &m_selection ? "selection" : "clipboard" ) << ":" << data.owner_is_qt;
#endif
}
void ClipboardPoll::timeout()
{
Klipper::updateTimestamp();
if( !kapp->clipboard()->ownsSelection() && checkTimestamp( m_selection ) ) {
#ifdef NOISY_KLIPPER_
kDebug() << "SELECTION CHANGED";
#endif
emit clipboardChanged( true );
}
if( !kapp->clipboard()->ownsClipboard() && checkTimestamp( m_clipboard ) ) {
#ifdef NOISY_KLIPPER_
kDebug() << "CLIPBOARD CHANGED";
#endif
emit clipboardChanged( false );
}
}
bool ClipboardPoll::checkTimestamp( SelectionData& data )
{
Window current_owner = XGetSelectionOwner( QX11Info::display(), data.atom );
bool signal = false;
updateQtOwnership( data );
if( data.owner_is_qt )
{
data.last_change = CurrentTime;
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "(3) Setting last_owner for =" << ( &data==&m_selection ?"selection":"clipboard" ) << ":" << current_owner;
#endif
data.last_owner = current_owner;
data.waiting_for_timestamp = false;
return false;
}
if( current_owner != data.last_owner )
{
signal = true; // owner has changed
data.last_owner = current_owner;
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "(4) Setting last_owner for =" << ( &data==&m_selection ?"selection":"clipboard" ) << ":" << current_owner;
#endif
data.waiting_for_timestamp = false;
data.last_change = CurrentTime;
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "OWNER CHANGE:" << ( data.atom == XA_PRIMARY ) << ":" << current_owner;
#endif
return true;
}
if( current_owner == None ) {
return false; // None also last_owner...
}
if( data.waiting_for_timestamp ) {
// We're already waiting for the timestamp of the last check
return false;
}
XDeleteProperty( QX11Info::display(), winId(), data.timestamp_atom );
XConvertSelection( QX11Info::display(), data.atom, m_xa_timestamp, data.timestamp_atom, winId(), QX11Info::appTime() );
data.waiting_for_timestamp = true;
data.waiting_x_time = QX11Info::appTime();
#ifdef REALLY_NOISY_KLIPPER_
kDebug() << "WAITING TIMESTAMP:" << ( data.atom == XA_PRIMARY );
#endif
return false;
}
bool ClipboardPoll::changedTimestamp( SelectionData& data, const XEvent& ev )
{
if( ev.xselection.requestor != winId()
|| ev.xselection.selection != data.atom
|| ev.xselection.time != data.waiting_x_time )
{
return false;
}
data.waiting_for_timestamp = false;
if( ev.xselection.property == None )
{
#ifdef NOISY_KLIPPER_
kDebug() << "REFUSED:" << ( data.atom == XA_PRIMARY );
#endif
return true;
}
Atom type;
int format;
unsigned long nitems;
unsigned long after;
unsigned char* prop = NULL;
if( XGetWindowProperty( QX11Info::display(), winId(), ev.xselection.property, 0, 1, False,
AnyPropertyType, &type, &format, &nitems, &after, &prop ) != Success
|| format != 32 || nitems != 1 || prop == NULL )
{
#ifdef NOISY_KLIPPER_
kDebug() << "BAD PROPERTY:" << ( data.atom == XA_PRIMARY );
#endif
if( prop != NULL )
XFree( prop );
return true;
}
Time timestamp = reinterpret_cast< long* >( prop )[ 0 ];
XFree( prop );
#ifdef NOISY_KLIPPER_
kDebug() << "GOT TIMESTAMP:" << ( data.atom == XA_PRIMARY );
kDebug() << "timestamp=" << timestamp
<< "; CurrentTime=" << CurrentTime
<< "; last_change=" << data.last_change
<< endl;
#endif
if( timestamp != data.last_change || timestamp == CurrentTime )
{
#ifdef NOISY_KLIPPER_
kDebug() << "TIMESTAMP CHANGE:" << ( data.atom == XA_PRIMARY );
#endif
data.last_change = timestamp;
return true;
}
return false; // ok, same timestamp
}
#include "clipboardpoll.moc"
| 11,828
|
C++
|
.cpp
| 310
| 32.935484
| 127
| 0.659061
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,111
|
qextserialenumerator.cpp
|
uwolfer_qtemu/GuestTools/qextserialport/qextserialenumerator.cpp
|
/**
* @file qextserialenumerator.cpp
* @author Michał Policht
* @see QextSerialEnumerator
*/
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
#ifdef _TTY_WIN_
notificationHandle = 0;
notificationWidget = 0;
#endif // _TTY_WIN_
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
#ifdef Q_OS_MAC
IONotificationPortDestroy( notificationPortRef );
#elif (defined _TTY_WIN_)
if( notificationHandle )
UnregisterDeviceNotification( notificationHandle );
if( notificationWidget )
delete notificationWidget;
#endif
}
#ifdef _TTY_WIN_
#include <objbase.h>
#include <initguid.h>
//this is serial port GUID
#ifndef GUID_CLASS_COMPORT
DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73);
#endif
/* Gordon Schumacher's macros for TCHAR -> QString conversions and vice versa */
#ifdef UNICODE
#define QStringToTCHAR(x) (wchar_t*) x.utf16()
#define PQStringToTCHAR(x) (wchar_t*) x->utf16()
#define TCHARToQString(x) QString::fromUtf16((ushort*)(x))
#define TCHARToQStringN(x,y) QString::fromUtf16((ushort*)(x),(y))
#else
#define QStringToTCHAR(x) x.local8Bit().constData()
#define PQStringToTCHAR(x) x->local8Bit().constData()
#define TCHARToQString(x) QString::fromLocal8Bit((x))
#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))
#endif /*UNICODE*/
//static
QString QextSerialEnumerator::getRegKeyValue(HKEY key, LPCTSTR property)
{
DWORD size = 0;
RegQueryValueEx(key, property, NULL, NULL, NULL, & size);
BYTE * buff = new BYTE[size];
QString result;
if (RegQueryValueEx(key, property, NULL, NULL, buff, & size) == ERROR_SUCCESS)
result = TCHARToQStringN(buff, size);
else
qWarning("QextSerialEnumerator::getRegKeyValue: can not obtain value from registry");
delete [] buff;
RegCloseKey(key);
return result;
}
//static
QString QextSerialEnumerator::getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property)
{
DWORD buffSize = 0;
SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, NULL, 0, & buffSize);
BYTE * buff = new BYTE[buffSize];
if (!SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, buff, buffSize, NULL))
qCritical("Can not obtain property: %ld from registry", property);
QString result = TCHARToQString(buff);
delete [] buff;
return result;
}
//static
void QextSerialEnumerator::setupAPIScan(QList<QextPortInfo> & infoList)
{
HDEVINFO devInfo = INVALID_HANDLE_VALUE;
GUID * guidDev = (GUID *) & GUID_CLASS_COMPORT;
devInfo = SetupDiGetClassDevs(guidDev, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if(devInfo == INVALID_HANDLE_VALUE) {
qCritical() << "SetupDiGetClassDevs failed:" << GetLastError();
return;
}
enumerateDevicesWin( devInfo, guidDev, &infoList );
}
void QextSerialEnumerator::enumerateDevicesWin( HDEVINFO devInfo, GUID* guidDev, QList<QextPortInfo>* infoList )
{
//enumerate the devices
bool ok = true;
SP_DEVICE_INTERFACE_DATA ifcData;
ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
PSP_DEVICE_INTERFACE_DETAIL_DATA detData = NULL;
DWORD detDataPredictedLength;
for (DWORD i = 0; ok; i++) {
ok = SetupDiEnumDeviceInterfaces(devInfo, NULL, guidDev, i, &ifcData);
if (ok)
{
SP_DEVINFO_DATA devData = {sizeof(SP_DEVINFO_DATA)};
//check for required detData size
SetupDiGetDeviceInterfaceDetail(devInfo, & ifcData, NULL, 0, &detDataPredictedLength, & devData);
detData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(detDataPredictedLength);
detData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
//check the details
if (SetupDiGetDeviceInterfaceDetail(devInfo, &ifcData, detData, detDataPredictedLength, NULL, & devData)) {
// Got a device. Get the details.
QextPortInfo info;
getDeviceDetailsWin( &info, devInfo, &devData );
infoList->append(info);
}
else
qCritical() << "SetupDiGetDeviceInterfaceDetail failed:" << GetLastError();
delete detData;
}
else if (GetLastError() != ERROR_NO_MORE_ITEMS) {
qCritical() << "SetupDiEnumDeviceInterfaces failed:" << GetLastError();
return;
}
}
SetupDiDestroyDeviceInfoList(devInfo);
}
bool QextSerialRegistrationWidget::winEvent( MSG* message, long* result )
{
if ( message->message == WM_DEVICECHANGE ) {
qese->onDeviceChangeWin( message->wParam, message->lParam );
*result = 1;
return true;
}
return false;
}
void QextSerialEnumerator::setUpNotificationWin( )
{
if(notificationWidget)
return;
notificationWidget = new QextSerialRegistrationWidget(this);
DEV_BROADCAST_DEVICEINTERFACE dbh;
ZeroMemory(&dbh, sizeof(dbh));
dbh.dbcc_size = sizeof(dbh);
dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
CopyMemory(&dbh.dbcc_classguid, &GUID_CLASS_COMPORT, sizeof(GUID));
notificationHandle = RegisterDeviceNotification( notificationWidget->winId( ), &dbh, DEVICE_NOTIFY_WINDOW_HANDLE );
if(!notificationHandle)
qWarning() << "RegisterDeviceNotification failed:" << GetLastError();
}
LRESULT QextSerialEnumerator::onDeviceChangeWin( WPARAM wParam, LPARAM lParam )
{
if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam )
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
if( pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE )
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
QString devId = TCHARToQString(pDevInf->dbcc_name);
// devId: \\?\USB#Vid_04e8&Pid_503b#0002F9A9828E0F06#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
devId.remove("\\\\?\\"); // USB#Vid_04e8&Pid_503b#0002F9A9828E0F06#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
devId.remove(QRegExp("#\\{(.+)\\}")); // USB#Vid_04e8&Pid_503b#0002F9A9828E0F06
devId.replace("#", "\\"); // USB\Vid_04e8&Pid_503b\0002F9A9828E0F06
devId = devId.toUpper();
//qDebug() << "devname:" << devId;
DWORD dwFlag = DBT_DEVICEARRIVAL == wParam ? (DIGCF_ALLCLASSES | DIGCF_PRESENT) : DIGCF_ALLCLASSES;
HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_CLASS_COMPORT,NULL,NULL,dwFlag);
SP_DEVINFO_DATA spDevInfoData;
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; SetupDiEnumDeviceInfo(hDevInfo, i, &spDevInfoData); i++)
{
DWORD nSize=0 ;
TCHAR buf[MAX_PATH];
if ( !SetupDiGetDeviceInstanceId(hDevInfo, &spDevInfoData, buf, sizeof(buf), &nSize) )
qDebug() << "SetupDiGetDeviceInstanceId():" << GetLastError();
if( devId == TCHARToQString(buf) ) // we found a match
{
QextPortInfo info;
getDeviceDetailsWin( &info, hDevInfo, &spDevInfoData, wParam );
if( wParam == DBT_DEVICEARRIVAL )
emit deviceDiscovered(info);
else if( wParam == DBT_DEVICEREMOVECOMPLETE )
emit deviceRemoved(info);
break;
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
}
return 0;
}
bool QextSerialEnumerator::getDeviceDetailsWin( QextPortInfo* portInfo, HDEVINFO devInfo, PSP_DEVINFO_DATA devData, WPARAM wParam )
{
portInfo->friendName = getDeviceProperty(devInfo, devData, SPDRP_FRIENDLYNAME);
if( wParam == DBT_DEVICEARRIVAL)
portInfo->physName = getDeviceProperty(devInfo, devData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME);
portInfo->enumName = getDeviceProperty(devInfo, devData, SPDRP_ENUMERATOR_NAME);
QString hardwareIDs = getDeviceProperty(devInfo, devData, SPDRP_HARDWAREID);
HKEY devKey = SetupDiOpenDevRegKey(devInfo, devData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
portInfo->portName = getRegKeyValue(devKey, TEXT("PortName"));
QRegExp rx("COM(\\d+)");
if(portInfo->portName.contains(rx))
{
int portnum = rx.cap(1).toInt();
if(portnum > 9)
portInfo->portName.prepend("\\\\.\\"); // COM ports greater than 9 need \\.\ prepended
}
QRegExp idRx("VID_(\\w+)&PID_(\\w+)&");
if( hardwareIDs.toUpper().contains(idRx) )
{
bool dummy;
portInfo->vendorID = idRx.cap(1).toInt(&dummy, 16);
portInfo->productID = idRx.cap(2).toInt(&dummy, 16);
//qDebug() << "got vid:" << vid << "pid:" << pid;
}
return true;
}
#endif /*_TTY_WIN_*/
#ifdef _TTY_POSIX_
#ifdef Q_OS_MAC
#include <IOKit/serial/IOSerialKeys.h>
#include <CoreFoundation/CFNumber.h>
#include <sys/param.h>
// static
void QextSerialEnumerator::scanPortsOSX(QList<QextPortInfo> & infoList)
{
io_iterator_t serialPortIterator = 0;
kern_return_t kernResult = KERN_FAILURE;
CFMutableDictionaryRef matchingDictionary;
// first try to get any serialbsd devices, then try any USBCDC devices
if( !(matchingDictionary = IOServiceMatching(kIOSerialBSDServiceValue) ) ) {
qWarning("IOServiceMatching returned a NULL dictionary.");
return;
}
CFDictionaryAddValue(matchingDictionary, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
// then create the iterator with all the matching devices
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
serialPortIterator = 0;
if( !(matchingDictionary = IOServiceNameMatching("AppleUSBCDC")) ) {
qWarning("IOServiceNameMatching returned a NULL dictionary.");
return;
}
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
}
void QextSerialEnumerator::iterateServicesOSX(io_object_t service, QList<QextPortInfo> & infoList)
{
// Iterate through all modems found.
io_object_t usbService;
while( ( usbService = IOIteratorNext(service) ) )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
getServiceDetailsOSX( usbService, &info );
infoList.append(info);
}
}
bool QextSerialEnumerator::getServiceDetailsOSX( io_object_t service, QextPortInfo* portInfo )
{
bool retval = true;
CFTypeRef bsdPathAsCFString = NULL;
CFTypeRef productNameAsCFString = NULL;
CFTypeRef vendorIdAsCFNumber = NULL;
CFTypeRef productIdAsCFNumber = NULL;
// check the name of the modem's callout device
bsdPathAsCFString = IORegistryEntryCreateCFProperty(service, CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault, 0);
// wander up the hierarchy until we find the level that can give us the
// vendor/product IDs and the product name, if available
io_registry_entry_t parent;
kern_return_t kernResult = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
while( kernResult == KERN_SUCCESS && !vendorIdAsCFNumber && !productIdAsCFNumber )
{
if(!productNameAsCFString)
productNameAsCFString = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR("Product Name"),
kCFAllocatorDefault, 0);
vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBVendorID),
kCFAllocatorDefault, 0);
productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBProductID),
kCFAllocatorDefault, 0);
io_registry_entry_t oldparent = parent;
kernResult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
IOObjectRelease(oldparent);
}
io_string_t ioPathName;
IORegistryEntryGetPath( service, kIOServicePlane, ioPathName );
portInfo->physName = ioPathName;
if( bsdPathAsCFString )
{
char path[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)bsdPathAsCFString, path,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->portName = path;
CFRelease(bsdPathAsCFString);
}
if(productNameAsCFString)
{
char productName[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)productNameAsCFString, productName,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->friendName = productName;
CFRelease(productNameAsCFString);
}
if(vendorIdAsCFNumber)
{
SInt32 vID;
if(CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberSInt32Type, &vID))
portInfo->vendorID = vID;
CFRelease(vendorIdAsCFNumber);
}
if(productIdAsCFNumber)
{
SInt32 pID;
if(CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberSInt32Type, &pID))
portInfo->productID = pID;
CFRelease(productIdAsCFNumber);
}
IOObjectRelease(service);
return retval;
}
// IOKit callbacks registered via setupNotifications()
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceDiscoveredOSX(serialService);
}
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceTerminatedOSX(serialService);
}
/*
A device has been discovered via IOKit.
Create a QextPortInfo if possible, and emit the signal indicating that we've found it.
*/
void QextSerialEnumerator::onDeviceDiscoveredOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceDiscovered( info );
}
/*
Notification via IOKit that a device has been removed.
Create a QextPortInfo if possible, and emit the signal indicating that it's gone.
*/
void QextSerialEnumerator::onDeviceTerminatedOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceRemoved( info );
}
/*
Create matching dictionaries for the devices we want to get notifications for,
and add them to the current run loop. Invoke the callbacks that will be responding
to these notifications once to arm them, and discover any devices that
are currently connected at the time notifications are setup.
*/
void QextSerialEnumerator::setUpNotificationOSX( )
{
kern_return_t kernResult;
mach_port_t masterPort;
CFRunLoopSourceRef notificationRunLoopSource;
CFMutableDictionaryRef classesToMatch;
CFMutableDictionaryRef cdcClassesToMatch;
io_iterator_t portIterator;
kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (KERN_SUCCESS != kernResult) {
qDebug() << "IOMasterPort returned:" << kernResult;
return;
}
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if (classesToMatch == NULL)
qDebug("IOServiceMatching returned a NULL dictionary.");
else
CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
if( !(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC") ) ) {
qWarning("couldn't create cdc matching dict");
return;
}
// Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);
notificationPortRef = IONotificationPortCreate(masterPort);
if(notificationPortRef == NULL) {
qDebug("IONotificationPortCreate return a NULL IONotificationPortRef.");
return;
}
notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
if (notificationRunLoopSource == NULL) {
qDebug("IONotificationPortGetRunLoopSource returned NULL CFRunLoopSourceRef.");
return;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
}
#endif // Q_OS_MAC
#endif // _TTY_POSIX_
//static
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> ports;
#ifdef _TTY_WIN_
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (!::GetVersionEx(&vi)) {
qCritical("Could not get OS version.");
return ports;
}
// Handle windows 9x and NT4 specially
if (vi.dwMajorVersion < 5) {
qCritical("Enumeration for this version of Windows is not implemented yet");
/*if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT)
EnumPortsWNt4(ports);
else
EnumPortsW9x(ports);*/
} else //w2k or later
setupAPIScan(ports);
#endif /*_TTY_WIN_*/
#ifdef _TTY_POSIX_
#ifdef Q_OS_MAC
scanPortsOSX(ports);
#else
qCritical("Enumeration for POSIX systems is not implemented yet.");
#endif /* Q_OS_MAC */
#endif /*_TTY_POSIX_*/
return ports;
}
void QextSerialEnumerator::setUpNotifications( )
{
#ifdef _TTY_WIN_
setUpNotificationWin( );
#endif
#ifdef _TTY_POSIX_
#ifdef Q_OS_MAC
(void)win;
setUpNotificationOSX( );
#else
qCritical("Notifications for *Nix/FreeBSD are not implemented yet");
#endif // Q_OS_MAC
#endif // _TTY_POSIX_
}
| 21,929
|
C++
|
.cpp
| 492
| 35.178862
| 135
| 0.650554
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
754,116
|
machineprocess.h
|
uwolfer_qtemu/machineprocess.h
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef MACHINEPROCESS_H
#define MACHINEPROCESS_H
#include <QObject>
#include <QProcess>
#include <QLocalSocket>
#include "qtemuenvironment.h"
#include "harddiskmanager.h"
class NetConfig;
class UsbConfig;
class MachineProcess : public QObject
{
Q_OBJECT
public:
enum ProcessState {NotRunning = 0, Starting = 1, Running = 2, Stopping = 3, Saving = 4};
MachineProcess(MachineTab *parent = 0);
qint64 write(const QByteArray & byteArray);
HardDiskManager* getHdManager();
UsbConfig* getUsbConfig();
QProcess* getProcess();
bool event(QEvent *event);
MachineProcess::ProcessState state();
public slots:
void start();
void resume(const QString& snapshotName = QString("Default"));
void suspend(const QString& snapshotName = QString("Default"));
void stop();
void forceStop();
void togglePause();
void changeCdrom();
void changeFloppy();
void loadCdrom();
void connectIfRunning();
signals:
void suspending(const QString & snapshotName);
void suspended(const QString & snapshotName);
void booting();
void resuming(const QString & snapshotName);
void resumed(const QString & snapshotName);
void error(const QString & errorText);
void stdout(const QString & stdoutText);
void stdin(const QString & stdoutText);
void rawConsole(const QString & consoleOutput);
void cleanConsole(const QString & consoleOutput);
void stateChanged(MachineProcess::ProcessState newState);
void started();
void finished();
private:
void getVersion();
void commitTmp();
void createTmp();
bool checkIfRunning();
void connectToProcess();
QStringList buildParamList();
QStringList buildEnvironment();
QString snapshotNameString;
QtEmuEnvironment env;
long versionMajor, versionMinor, versionBugfix, kvmVersion;
bool paused;
bool doResume;
HardDiskManager *hdManager;
QString lastOutput;
QStringList outputParts;
MachineProcess::ProcessState myState;
NetConfig *netConfig;
UsbConfig *usbConfig;
QLocalSocket *console;
QProcess *process;
private slots:
void beforeRunExecute();
void afterExitExecute();
void readProcess();
void readProcessErrors();
void writeDebugInfo(const QString& debugText);
void resumeFinished(const QString& returnedText);
void suspendFinished(const QString& returnedText);
void deleteTmp(int successfulCommit);
void saveState(MachineProcess::ProcessState newState);
};
#endif
| 3,600
|
C++
|
.h
| 102
| 31.686275
| 92
| 0.710587
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,117
|
halobject.h
|
uwolfer_qtemu/halobject.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef HALOBJECT_H
#define HALOBJECT_H
#include <QObject>
#include <QStandardItemModel>
#include <QDBusInterface>
#include <QDBusReply>
#include <QHash>
struct UsbDevice
{
QString id;
QString vendor;
QString product;
QString address;
};
struct OptDevice
{
QString device;
QString id;
QString name;
QString volume;
QString volumeId;
};
class HalObject : public QObject
{
Q_OBJECT
public:
HalObject();
const QStringList deviceList();
const QList<UsbDevice> usbList();
const QStringList ifList();
const QList<OptDevice> opticalList();
private:
QStringList getDevices();
QDBusInterface *hal;
QHash<QString, UsbDevice> usbDeviceHash;
QHash<QString, OptDevice> optDeviceHash;
signals:
//generic catchall device notification
void deviceAdded(const QString devString);
void deviceRemoved(const QString devString);
//ethernet notifications
void ifAdded(const QString ifName, const QString macAddr);
void ifRemoved(const QString ifName, const QString macAddr);
//might need if activated/deactivated notifications
//optical drive notifications
void opticalAdded(const QString devName, const QString devPath);
void opticalRemoved(const QString devName, const QString devPath);
//floppy drive notifications
void floppyAdded(const QString devName, const QString devPath);
void floppyRemoved(const QString devName, const QString devPath);
//usb notifications
void usbAdded(const QString devString, const UsbDevice device);
void usbRemoved(const QString devString, const UsbDevice device);
private slots:
void halDeviceAdded(const QString name);
void halDeviceRemoved(const QString name);
};
#endif // HALOBJECT_H
| 2,793
|
C++
|
.h
| 80
| 31.65
| 77
| 0.715399
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,118
|
settingstab.h
|
uwolfer_qtemu/settingstab.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef SETTINGSTAB_H
#define SETTINGSTAB_H
#include "ui_settingstab.h"
#include "machineprocess.h"
#include "machinetab.h"
#include <QFrame>
class MachineConfigObject;
class NetworkPage;
class UsbPage;
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class SettingsTab : public QFrame, public Ui::SettingsTab
{
Q_OBJECT
public:
explicit SettingsTab(MachineConfigObject *config, MachineTab *parent = 0);
~SettingsTab();
UsbPage *getUsbPage();
public slots:
void setNewCdImagePath();
void setNewFloppyImagePath();
void setVirtSize(qint64 size);
void setPhySize(qint64 size);
private:
MachineConfigObject *config;
MachineTab *parent;
QString myMachinesPath;
NetworkPage *netPage;
UsbPage *usbPageWidget;
void registerWidgets();
void setupHelp();
void setupConnections();
void getSettings();
void getDrives();
void disableUnsupportedOptions();
private slots:
void changeHelpTopic();
//file select dialogs
void setNewHddPath();
//warning dialogs
void confirmUpgrade();
void optAdded(const QString devName, const QString devPath);
void optRemoved(const QString devName, const QString devPath);
signals:
void upgradeHdd();
};
#endif
| 2,264
|
C++
|
.h
| 70
| 29.614286
| 78
| 0.70202
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,119
|
controlpanel.h
|
uwolfer_qtemu/controlpanel.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
/****************************************************************************
** C++ Interface: controlpanel
**
** Description:
**
****************************************************************************/
#ifndef CONTROLPANEL_H
#define CONTROLPANEL_H
#include "ui_controlpanel.h"
#include <QWidget>
class MachineTab;
class MachineConfigObject;
class MachineProcess;
class SettingsTab;
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class ControlPanel : public QWidget , public Ui::ControlPanel
{
Q_OBJECT
public:
explicit ControlPanel(MachineTab *parent);
~ControlPanel();
private:
void makeConnections();
void registerObjects();
MachineTab *parent;
MachineConfigObject *config;
private slots:
void mediaActivate();
void displayActivate();
void usbActivate();
void saveScreenshot();
void running();
void stopped();
void optionChanged(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value);
void optAdded(const QString devName, const QString devPath);
void optRemoved(const QString devName, const QString devPath);
};
#endif
| 2,162
|
C++
|
.h
| 62
| 32.725806
| 123
| 0.648494
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,121
|
networkpage.h
|
uwolfer_qtemu/networkpage.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef NETWORKPAGE_H
#define NETWORKPAGE_H
#include <QWidget>
#include <QModelIndex>
#include "ui_networkpage.h"
class MachineConfigObject;
class GuestInterfaceModel;
class HostInterfaceModel;
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
/****************************************************************************
** C++ Interface: networkpage
**
** Description:
**
****************************************************************************/
class NetworkPage : public QWidget , public Ui::NetworkPage
{
Q_OBJECT
public:
explicit NetworkPage(MachineConfigObject *config, QWidget *parent = 0);
~NetworkPage();
private:
void makeConnections();
void setupPage();
void setupModels();
void registerObjects();
MachineConfigObject *config;
GuestInterfaceModel *guestModel;
HostInterfaceModel *hostModel;
bool changingSelection;
//dealing with model/view
private slots:
void changeNetPage(bool state);
void delGuestInterface();
void addGuestInterface();
void delHostInterface();
void addHostInterface();
void guestSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected);
void hostSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected);
void loadHostEthIfs();
};
//class hostInterfaceModel;
#endif
| 2,367
|
C++
|
.h
| 67
| 32.925373
| 99
| 0.664474
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,122
|
configwindow.h
|
uwolfer_qtemu/configwindow.h
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef CONFIGWINDOW_H
#define CONFIGWINDOW_H
#include <QDialog>
class QLineEdit;
class QComboBox;
class QTextEdit;
class QCheckBox;
class ConfigWindow : public QDialog
{
Q_OBJECT
public:
ConfigWindow(const QString &myMachinesPath, int tabPosition, QWidget *parent = 0);
QLineEdit *myMachinePathLineEdit;
QComboBox *comboTabPosition;
QComboBox *languagePosition;
private:
QString myMachinesPath;
QTextEdit *beforeStartExeTextEdit;
QTextEdit *afterExitExeTextEdit;
QLineEdit *commandLineEdit;
QComboBox *comboIconTheme;
private slots:
void setNewPath();
void languageChange(int index);
void loadSettings();
void writeSettings();
};
#endif
| 1,714
|
C++
|
.h
| 50
| 31.98
| 86
| 0.696073
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,123
|
helpwindow.h
|
uwolfer_qtemu/helpwindow.h
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef HELPWINDOW_H
#define HELPWINDOW_H
#include <QDialog>
#include <QUrl>
class HelpWindow : public QDialog
{
Q_OBJECT
public:
HelpWindow(QWidget *parent = 0);
static QUrl getHelpLocation();
private slots:
QUrl getHelpFile();
};
#endif
| 1,271
|
C++
|
.h
| 36
| 33.722222
| 77
| 0.65935
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,124
|
usbpage.h
|
uwolfer_qtemu/usbpage.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef USBPAGE_H
#define USBPAGE_H
#include <QWidget>
#include "ui_usbpage.h"
class MachineConfigObject;
class UsbModel;
class UsbPage : public QWidget , public Ui::UsbPage
{
Q_OBJECT
public:
UsbPage(MachineConfigObject *config, QWidget *parent);
~UsbPage();
UsbModel* getModel();
private:
MachineConfigObject *config;
void registerWidgets();
UsbModel *model;
};
#endif // USBPAGE_H
| 1,430
|
C++
|
.h
| 41
| 33.073171
| 77
| 0.673188
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,125
|
machineconfig.h
|
uwolfer_qtemu/machineconfig.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef MACHINECONFIG_H
#define MACHINECONFIG_H
#include <QObject>
#include <QDomElement>
#include <QVariant>
class QFile;
class QDomDocument;
class QStringList;
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class MachineConfig : public QObject
{
Q_OBJECT
public:
explicit MachineConfig(QObject *parent = 0, const QString &store = QString());
~MachineConfig();
bool loadConfig(const QString &fileName);
bool saveConfig(const QString &fileName) const;
bool convertConfig(const QString &fileName) const;
//if nodeType and nodeName are not specified, they are assumed to be "machine" and ""
QVariant getOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant defaultValue = QVariant());
QStringList getAllOptionNames(const QString &nodeType, const QString &nodeName) const;
int getNumOptions(const QString &nodeType, const QString &nodeName) const;
public slots:
//if nodeType and nodeName are not specified, they are assumed to be "machine" and ""
void setOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value);
void clearOption(const QString &nodeType, const QString &nodeName, const QString &optionName);
signals:
void optionChanged(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value);
private:
QFile *configFile;
QDomDocument domDocument;
QDomElement root;
};
#endif
| 2,510
|
C++
|
.h
| 58
| 40.896552
| 142
| 0.720558
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,126
|
machineview.h
|
uwolfer_qtemu/machineview.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop @ gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef MACHINEVIEW_H
#define MACHINEVIEW_H
#include "vnc/vncview.h"
#include "machinesplash.h"
#include "floatingtoolbar.h"
#include "machineconfigobject.h"
#include "machinescrollarea.h"
#include <QScrollArea>
#include <QEvent>
#include <QResizeEvent>
#include <QMouseEvent>
#include <QDynamicPropertyChangeEvent>
#include <QSvgWidget>
#include <QShortcut>
#include <QPalette>
#include <QWidget>
#include <QApplication>
#include <QDesktopWidget>
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class MachineView : public QWidget
{
Q_OBJECT
public:
explicit MachineView(MachineConfigObject *config, QWidget *parent = 0);
~MachineView();
void showSplash(bool show);
void captureAllKeys(bool enabled);
void sendKey(QKeyEvent *event);
bool event(QEvent * event);
public slots:
void newViewSize();
void fullscreen(bool enable);
void initView();
private slots:
void showToolBar();
signals:
void fullscreenToggled(bool enabled);
private:
VncView *view;
MachineSplash *splash;
FloatingToolBar *toolBar;
MachineConfigObject *config;
QWidget *fullscreenWindow;
MachineScrollArea *fullscreenScrollArea;
MachineScrollArea *embeddedScrollArea;
bool fullscreenEnabled;
int port;
//actions... will later be moved to its own file
QAction *scaleAction;
};
class MinimizePixel : public QWidget
{
Q_OBJECT
public:
MinimizePixel(QWidget *parent)
: QWidget(parent) {
setFixedSize(1, 1);
move(QApplication::desktop()->screenGeometry().width() - 1, 0);
}
signals:
void rightClicked();
protected:
void mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::RightButton)
emit rightClicked();
}
};
#endif
| 2,792
|
C++
|
.h
| 92
| 27.369565
| 77
| 0.699888
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,127
|
harddiskmanager.h
|
uwolfer_qtemu/harddiskmanager.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef HARDDISKMANAGER_H
#define HARDDISKMANAGER_H
#include <QObject>
#include <QEvent>
#include <QFileInfo>
#include "machinetab.h"
class QTimer;
class QProcess;
class MachineProcess;
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class HardDiskManager : public QObject
{
Q_OBJECT
public:
HardDiskManager(MachineProcess *parent = 0);
~HardDiskManager();
bool imageIs();
bool event(QEvent * event);
bool isSuspendable() const;
private:
void addDisk(const QString &path, const int address);
//data
QStringList diskImages;
//used for some functions
MachineProcess *parent;
QString upgradeImageName;
QTimer *updateProgressTimer;
QProcess *currentProcess;
QString currentFormat;
QFileInfo currentImage;
qint64 virtualSize;
qint64 oldSize;
bool suspendable;
bool resumable;
public slots:
void upgradeImage();
void testImage();
private slots:
void upgradeComplete(int status);
void updateUpgradeProgress();
signals:
void processingImage(bool processing);
void imageUpgradable(bool elegability);
void upgradeProgress(qint64 size, qint64 total);
void error(const QString &errorString);
void imageFormat(QString format);
void imageSize(qint64 size);
void phySize(qint64 size);
void supportsSuspending(bool status);
void supportsResuming(bool status);
};
#endif
| 2,406
|
C++
|
.h
| 76
| 28.881579
| 77
| 0.708981
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,128
|
netconfig.h
|
uwolfer_qtemu/netconfig.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef NETCONFIG_H
#define NETCONFIG_H
//
#include <QObject>
#include <QString>
#include <QList>
#include <QStringList>
class MachineConfigObject;
class GuestInterface;
class HostInterface;
class HostActionItem;
class NetConfig : public QObject
{
Q_OBJECT
public:
explicit NetConfig(QObject *parent = 0, MachineConfigObject *config = 0);
MachineConfigObject *config;
QStringList getOptionString();
private:
void buildIfs();
QList<GuestInterface*> *guestIfs;
QList<HostInterface*> *hostIfs;
QStringList hostIfNames;
QList<HostActionItem*> *startActions;
QList<HostActionItem*> *stopActions;
};
class NetInterface : public QObject
{
Q_OBJECT
public:
explicit NetInterface(NetConfig *parent = 0, QString nodeType = QString(), QString nodeName = QString());
int getVlan();
void setVlan(int number);
virtual QStringList parseOpts();
int vlan;
private:
protected:
MachineConfigObject *config;
QString nodeType;
QString nodeName;
QString type;
};
class GuestInterface : public NetInterface
{
Q_OBJECT
public:
explicit GuestInterface(NetConfig *parent = 0, QString nodeName = QString());
virtual QStringList parseOpts();
};
class HostInterface : public NetInterface
{
Q_OBJECT
public:
explicit HostInterface(NetConfig *parent = 0, QString nodeName = QString());
virtual QStringList parseOpts();
};
class HostActionItem : public QObject
{
enum HostAction { Add, RemoveIfUnused, Remove };
enum HostItem { Bridge, Tap, Connection, Route};
Q_OBJECT
public:
HostActionItem(NetConfig *parent, HostAction action, HostItem item, QString interface, QString interfaceTo = QString());
bool performAction();
private:
HostAction action;
HostItem item;
QString interface;
QString toInterface;
};
#endif
| 2,860
|
C++
|
.h
| 93
| 27.978495
| 124
| 0.717431
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,129
|
mainwindow.h
|
uwolfer_qtemu/mainwindow.h
|
/****************************************************************************
**
** Copyright (C) 2006-2008 Urs Wolfer <uwolfer @ fwo.ch>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class QAction;
class QMenu;
class QTabWidget;
class QPushButton;
class QWidget;
class QLabel;
class QStringList;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
protected:
void closeEvent(QCloseEvent *event);
private slots:
void createNew();
void open();
void configure();
void start();
void pause();
void stop();
void restart();
void about();
void help();
void changeMachineState(int value = -1);
private:
void createActions();
void createMenus();
void createToolBars();
void createStatusBar();
void createMainTab();
void readSettings();
void writeSettings();
void loadFile(const QString &fileName);
QTabWidget *tabWidget;
QMenu *fileMenu;
QMenu *powerMenu;
QMenu *helpMenu;
QToolBar *fileToolBar;
QToolBar *powerToolBar;
QAction *newAct;
QAction *openAct;
QAction *confAct;
QAction *exitAct;
QAction *startAct;
QAction *stopAct;
QAction *restartAct;
QAction *pauseAct;
QAction *helpAct;
QAction *aboutAct;
QWidget *mainTabWidget;
QLabel *mainTabLabel;
QPushButton *newButton;
QPushButton *openButton;
QString myMachinesPath;
QString iconTheme;
};
#endif
| 2,339
|
C++
|
.h
| 83
| 24.963855
| 77
| 0.677807
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,130
|
qtemuenvironment.h
|
uwolfer_qtemu/qtemuenvironment.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef QTEMUENVIRONMENT_H
#define QTEMUENVIRONMENT_H
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class HalObject;
class QtEmuEnvironment{
public:
QtEmuEnvironment();
~QtEmuEnvironment();
///returned as an array with 3 members: major version, minor version, and bugfix version.
static int* getQemuVersion();
///just a plain old number
static int getKvmVersion();
static HalObject* getHal();
static bool kvmSupport();
static bool kqemuSupport();
private:
static void getVersion();
static int qemuVersion[3];
static int kvmVersion;
static bool versionChecked;
static bool supportsKvm;
static bool supportsKqemu;
static HalObject *hal;
};
#endif
| 1,731
|
C++
|
.h
| 49
| 32.959184
| 89
| 0.684211
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,131
|
usbmodel.h
|
uwolfer_qtemu/usbmodel.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef USBMODEL_H
#define USBMODEL_H
#include <QStandardItemModel>
#include "halobject.h"
class MachineConfigObject;
class UsbModel : public QStandardItemModel
{
Q_OBJECT
public:
UsbModel(MachineConfigObject * config, QObject * parent);
private:
void getUsbDevices();
void loadConfig();
void checkDevice(QString deviceName);
void addItem(QString deviceName, QString id);
MachineConfigObject *config;
HalObject *hal;
private slots:
void getChange(QStandardItem * item);
void deviceAdded(QString name, UsbDevice device);
void deviceRemoved(QString name, UsbDevice device);
signals:
void vmDeviceAdded(QString identifier);
void vmDeviceRemoved(QString identifier);
};
#endif // USBMODEL_H
| 1,762
|
C++
|
.h
| 48
| 34.416667
| 77
| 0.697183
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,132
|
machineconfigobject.h
|
uwolfer_qtemu/machineconfigobject.h
|
/****************************************************************************
**
** Copyright (C) 2008 Ben Klopfenstein <benklop@gmail.com>
**
** This file is part of QtEmu.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU Library General Public License
** along with this library; see the file COPYING.LIB. If not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
** Boston, MA 02110-1301, USA.
**
****************************************************************************/
#ifndef MACHINECONFIGOBJECT_H
#define MACHINECONFIGOBJECT_H
#include <QObject>
#include <QVariant>
#include <QList>
#include "machineconfig.h"
/**
@author Ben Klopfenstein <benklop@gmail.com>
*/
class MachineConfigObject : public QObject
{
Q_OBJECT
public:
explicit MachineConfigObject(QObject *parent = 0, MachineConfig *config = 0);
~MachineConfigObject();
/**
add an object to the list along with the config option it uses, stored in the object as a property.
*/
void registerObject(QObject *object, const QString &nodeType, const QString &nodeName, const QString &optionName = QString(), const QVariant &defaultValue = QVariant());
/**
registers an object using the short syntax
*/
void registerObject(QObject *object, const QString &optionName = QString(), const QVariant &defaultValue = QVariant());
/**
unregister an object
*/
void unregisterObject(QObject *object);
/**
event handler for intercepting changes in objects with multiple properties
*/
bool eventFilter(QObject *object, QEvent *event);
/**
sets the config object to use (config file object)
*/
void setConfig(MachineConfig *config);
/**
gets the config object used (config file object)
*/
MachineConfig* getConfig();
/**
get an option from the config file
*/
QVariant getOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &defaultValue);
/**
get an option from the config file using the short syntax
*/
QVariant getOption(const QString &optionName, const QVariant &defaultValue = QVariant());
public slots:
/**
sets an option in the config file
*/
void setOption(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value);
/**
set an option in the config file using the short syntax
*/
void setOption(const QString &optionName, const QVariant &value);
/**
slot is activated if there is a config change
*/
void configChanged(const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &value);
/**
get the value of the calling object and sets the value of the associated config option
*/
void getObjectValue();
private:
QList<QObject *> registeredObjects;
MachineConfig *myConfig;
/**
set an object to the value of its associated config option, or default
*/
void setObjectValue(QObject *object, const QString &nodeType, const QString &nodeName, const QString &optionName, const QVariant &defaultValue = QVariant());
};
#endif
| 3,574
|
C++
|
.h
| 95
| 35.105263
| 173
| 0.720775
|
uwolfer/qtemu
| 136
| 54
| 23
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.