diff --git a/docs/img/ar_SA.svg b/docs/img/ar_SA.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/ar_SA.svg +++ b/docs/img/ar_SA.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/cs_CZ.svg b/docs/img/cs_CZ.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/cs_CZ.svg +++ b/docs/img/cs_CZ.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/de_DE.svg b/docs/img/de_DE.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/de_DE.svg +++ b/docs/img/de_DE.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/en_US.svg b/docs/img/en_US.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/en_US.svg +++ b/docs/img/en_US.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/es_ES.svg b/docs/img/es_ES.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/es_ES.svg +++ b/docs/img/es_ES.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/fr_FR.svg b/docs/img/fr_FR.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/fr_FR.svg +++ b/docs/img/fr_FR.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/ja_JP.svg b/docs/img/ja_JP.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/ja_JP.svg +++ b/docs/img/ja_JP.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/ko_KR.svg b/docs/img/ko_KR.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/ko_KR.svg +++ b/docs/img/ko_KR.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/pt_BR.svg b/docs/img/pt_BR.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/pt_BR.svg +++ b/docs/img/pt_BR.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/ru_RU.svg b/docs/img/ru_RU.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/ru_RU.svg +++ b/docs/img/ru_RU.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/zh_CN.svg b/docs/img/zh_CN.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/zh_CN.svg +++ b/docs/img/zh_CN.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/docs/img/zh_HK.svg b/docs/img/zh_HK.svg index 5fb85acf..93c4aaa3 100644 --- a/docs/img/zh_HK.svg +++ b/docs/img/zh_HK.svg @@ -1 +1 @@ -869/869 (100.0%) \ No newline at end of file +868/868 (100.0%) \ No newline at end of file diff --git a/lang/quardCRT_ar_SA.ts b/lang/quardCRT_ar_SA.ts index 1dac90f9..14367e59 100644 --- a/lang/quardCRT_ar_SA.ts +++ b/lang/quardCRT_ar_SA.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar شريط الأدوات @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning تحذير @@ -285,7 +285,7 @@ - + Ready جاهز @@ -464,7 +464,7 @@ - + Help مساعدة @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect أدخل المضيف <Alt+R> للاتصال - + Disconnect All قطع الاتصال بالكل - + Disconnect all sessions قطع الاتصال بجميع الجلسات - + Clone Session استنساخ الجلسة - + Clone current session <Ctrl+Shift+T> استنساخ الجلسة الحالية <Ctrl+Shift+T> @@ -595,564 +596,564 @@ قفل الجلسة - + Log Session سجل الجلسة - + Create a log file for current session إنشاء ملف سجل للجلسة الحالية - + Raw Log Session سجل الجلسة الخام - + Create a raw log file for current session إنشاء ملف سجل خام للجلسة الحالية - + Hex View عرض Hex - + Show/Hide Hex View for current session إظهار/إخفاء عرض Hex للجلسة الحالية - + Exit خروج - + Quit the application إنهاء التطبيق - + Copy نسخ - + Copy the selected text to the clipboard <Command+C> نسخ النص المحدد إلى الحافظة <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> نسخ النص المحدد إلى الحافظة <Ctrl+Ins> - + Paste لصق - + Paste the clipboard text to the current session <Command+V> لصق نص الحافظة في الجلسة الحالية <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> لصق نص الحافظة في الجلسة الحالية <Shift+Ins> - + Copy and Paste نسخ ولصق - + Copy the selected text to the clipboard and paste to the current session نسخ النص المحدد إلى الحافظة ولصقه في الجلسة الحالية - + Select All تحديد الكل - + Select all text in the current session <Ctrl+Shift+A> تحديد كل النص في الجلسة الحالية <Ctrl+Shift+A> - + Find... البحث... - + Find text in the current session <Ctrl+F> البحث عن نص في الجلسة الحالية <Ctrl+F> - + Print Screen طباعة الشاشة - + Print current screen طباعة الشاشة الحالية - + Screen Shot لقطة الشاشة - + Screen shot current screen <Alt+P> لقطة شاشة الشاشة الحالية <Alt+P> - + Session Export تصدير الجلسة - + Export current session to a file <Alt+O> تصدير الجلسة الحالية إلى ملف <Alt+O> - + Clear Scrollback مسح السجل الراجع - + Clear the contents of the scrollback rows مسح محتويات صفوف السجل الراجع - + Clear Screen مسح الشاشة - + Clear the contents of the current screen مسح محتويات الشاشة الحالية - + Clear Screen and Scrollback مسح الشاشة والسجل الراجع - + Clear the contents of the screen and scrollback مسح محتويات الشاشة والسجل الراجع - + Reset إعادة تعيين - + Reset terminal emulator إعادة تعيين محاكي الطرفية - + Zoom In تكبير - + Zoom In <Ctrl+"="> تكبير <Ctrl+"="> - + Zoom Out تصغير - + Zoom Out <Ctrl+"-"> تصغير <Ctrl+"-"> - - + + Zoom Reset إعادة تعيين التكبير - + Layout التخطيط - + Single Layout تخطيط واحد - + Single layout تخطيط واحد - + Two Columns Layout تخطيط عمودين - + Two columns layout تخطيط عمودين - + Three Columns Layout تخطيط ثلاثة أعمدة - + Three columns layout تخطيط ثلاثة أعمدة - + Two Rows Layout تخطيط صفين - + Two rows layout تخطيط صفين - + Three Rows Layout تخطيط ثلاثة صفوف - + Three rows layout تخطيط ثلاثة صفوف - + Grid Layout تخطيط الشبكة - + Grid layout تخطيط الشبكة - + Two Rows Right Layout تخطيط صفين إلى اليمين - + Two rows right layout تخطيط صفين إلى اليمين - + Two Columns Bottom Layout تخطيط عمودين أسفل - + Two columns bottom layout تخطيط عمودين أسفل - + Flip Layout قلب التخطيط - + Flip layout قلب التخطيط - + Menu Bar شريط القائمة - + Show/Hide Menu Bar <Alt+U> إظهار/إخفاء شريط القائمة <Alt+U> - + Show/Hide Tool Bar إظهار/إخفاء شريط الأدوات - + Status Bar شريط الحالة - + Show/Hide Status Bar إظهار/إخفاء شريط الحالة - + Command Window نافذة الأمر - + Show/Hide Command Window إظهار/إخفاء نافذة الأمر - + Connect Bar شريط الاتصال - + Show/Hide Connect Bar إظهار/إخفاء شريط الاتصال - + Side Window النافذة الجانبية - + Show/Hide Side Window إظهار/إخفاء النافذة الجانبية - + Windows Transparency شفافية النوافذ - + Enable/Disable alpha transparency تمكين/تعطيل الشفافية ألفا - + Vertical Scroll Bar شريط التمرير العمودي - + Show/Hide Vertical Scroll Bar إظهار/إخفاء شريط التمرير العمودي - + Allways On Top دائمًا في الأعلى - + Show window always on top إظهار النافذة دائمًا في الأعلى - + Full Screen شاشة كاملة - + Toggle between full screen and normal mode <Alt+Enter> التبديل بين وضع الشاشة الكاملة والوضع العادي <Alt+Enter> - + Session Options... خيارات الجلسة... - + Configure session options تكوين خيارات الجلسة - + Global Options... الخيارات العامة... - + Configure global options تكوين الخيارات العامة - + Real-time Save Options خيارات الحفظ في الوقت الحقيقي - + Real-time save session options and global options حفظ خيارات الجلسة والخيارات العامة في الوقت الحقيقي - + Save Settings Now حفظ الإعدادات الآن - + Save options configuration now حفظ تكوين الخيارات الآن - + Send ASCII... إرسال ASCII... - + Send ASCII file إرسال ملف ASCII - + Receive ASCII... استقبال ASCII... - + Receive ASCII file استقبال ملف ASCII - + Send Binary... إرسال ثنائي... - + Send Binary file إرسال ملف ثنائي - + Send Kermit... إرسال Kermit... - + Send a file using Kermit إرسال ملف باستخدام Kermit - + Receive Kermit... استقبال Kermit... - + Receive a file using Kermit استقبال ملف باستخدام Kermit - + Send Xmodem... إرسال Xmodem... - + Send a file using Xmodem إرسال ملف باستخدام Xmodem - + Receive Xmodem... استقبال Xmodem... - + Receive a file using Xmodem استقبال ملف باستخدام Xmodem - + Send Ymodem... إرسال Ymodem... - + Send a file using Ymodem إرسال ملف باستخدام Ymodem - + Receive Ymodem... استقبال Ymodem... - + Receive a file using Ymodem استقبال ملف باستخدام Ymodem - + Zmodem Upload List... قائمة تحميل Zmodem... - + Display Zmodem file upload list عرض قائمة تحميل ملف Zmodem - + Start Zmodem Upload بدء تحميل Zmodem - + Start Zmodem file upload بدء تحميل ملف Zmodem - + Start TFTP Server بدء خادم TFTP - + Start/Stop the TFTP server بدء/إيقاف خادم TFTP - + Run... تشغيل... - + Run a script تشغيل نصًا - + Cancel إلغاء @@ -1213,759 +1214,759 @@ تغيير اللون - + Cancel script execution إلغاء تنفيذ النص - + Start Recording Script بدء تسجيل النص - + Start recording script بدء تسجيل النص - + Stop Recording Script... إيقاف تسجيل النص... - + Stop recording script إيقاف تسجيل النص - + Cancel Recording Script إلغاء تسجيل النص - + Cancel recording script إلغاء تسجيل النص - + Add Bookmark إضافة إشارة مرجعية - + Add a bookmark إضافة إشارة مرجعية - - + + Remove Bookmark إزالة الإشارة المرجعية - + Remove a bookmark إزالة إشارة مرجعية - - + + Clean All Bookmark تنظيف كل الإشارات المرجعية - + Clean all bookmark تنظيف كل الإشارات المرجعية - + Keymap Manager مدير الخريطة الرئيسية - + Display keymap editor عرض محرر الخريطة الرئيسية - + Create Public Key... إنشاء مفتاح عام... - + Create a public key إنشاء مفتاح عام - + Publickey Manager مدير المفتاح العام - + Display publickey manager عرض مدير المفتاح العام - + Internal Command الأمر الداخلي - + Display Internal Command window عرض نافذة الأمر الداخلي - + Tab لسان - + Arrange sessions in tabs ترتيب الجلسات في علامات التبويب - + Tile بلاطة - + Arrange sessions in non-overlapping tiles ترتيب الجلسات في بلاطات غير متداخلة - + Cascade شلال - + Arrange sessions to overlap each other ترتيب الجلسات لتتداخل مع بعضها البعض - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Light خفيف - + Switch to light theme التبديل إلى السمة الفاتحة - + Dark داكن - + Switch to dark theme التبديل إلى السمة الداكنة - + Theme Color لون السمة - + Set theme color, cancel to use default تعيين لون السمة، إلغاء لاستخدام الافتراضي - + Display help عرض المساعدة - - + + Keyborad Shortcuts Reference مرجع اختصارات لوحة المفاتيح - + Display keyborad shortcuts reference عرض مرجع اختصارات لوحة المفاتيح - + Check Update التحقق من التحديث - + Check for updates التحقق من وجود تحديثات - - + + Privacy Statement بيان الخصوصية - + Display privacy statement عرض بيان الخصوصية - - + + About حول - + Display about dialog عرض مربع الحوار حول - + About Qt حول Qt - + Display about Qt dialog عرض مربع الحوار حول Qt - - + + About Python حول Python - + Display about Python dialog عرض مربع الحوار حول Python - + Laboratory مختبر - - + + SSH Scanning فحص SSH - + Display SSH scanning dialog عرض مربع الحوار فحص SSH - + Plugin Info معلومات البرنامج المساعد - + Display plugin information dialog عرض مربع الحوار معلومات البرنامج المساعد - + Plugin metaData not found! لم يتم العثور على بيانات البرنامج المساعد! - + Plugin api version not found! لم يتم العثور على إصدار واجهة برمجة التطبيقات للبرنامج المساعد! - + Plugin api version not match! إصدار واجهة برمجة التطبيقات للبرنامج المساعد لا يتطابق! - + Plugin menu not found! لم يتم العثور على قائمة البرنامج المساعد! - + Plugin init failed! فشل تهيئة البرنامج المساعد! - + PrintScreen saved to %1 تم حفظ PrintScreen في %1 - + Save Screenshot حفظ لقطة الشاشة - + Image Files (*.jpg) ملفات الصور (*.jpg) - - + + Screenshot saved to %1 تم حفظ لقطة الشاشة في %1 - + Save Session Export حفظ تصدير الجلسة - + Text Files (*.txt);;HTML Files (*.html) ملفات النص (*.txt);;ملفات HTML (*.html) - + Text Files (*.txt) ملفات النص (*.txt) - + HTML Files (*.html) ملفات HTML (*.html) - + Session Export saved to %1 تم حفظ تصدير الجلسة في %1 - + Session Export failed to save to %1 فشل حفظ تصدير الجلسة في %1 - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! لا يمكن لجلسة البث نقل الملف! - + Select Files to Send as ASCII حدد الملفات لإرسالها كـ ASCII - - + + Text Files (*.txt);;All Files (*) ملفات النص (*.txt);;كل الملفات (*) - + Save Received Data as ASCII حفظ البيانات المستلمة كـ ASCII - + Select Files to Send as BINARY حدد الملفات لإرسالها كـ BINARY - - - - - - + + + + + + All Files (*) كل الملفات (*) - + Select Files to Send using Kermit حدد الملفات لإرسالها باستخدام Kermit - + Select Files to Send using Xmodem حدد الملفات لإرسالها باستخدام Xmodem - + Save Received Files using Xmodem حفظ الملفات المستلمة باستخدام Xmodem - + Select Files to Send using Ymodem حدد الملفات لإرسالها باستخدام Ymodem - + Select Files to Send using Zmodem حدد الملفات لإرسالها باستخدام Zmodem - + Select a script file حدد ملف نصي - + Python Files (*.py);;All Files (*) ملفات Python (*.py);;كل الملفات (*) - + Select a directory حدد دليلًا - + Select a bookmark حدد إشارة مرجعية - + Are you sure to clean all bookmark? هل أنت متأكد من تنظيف كل الإشارات المرجعية؟ - + Port منفذ - + Select color حدد لونًا - + Video background is enabled, please enable animation in global options (more system resources) or change background image. تم تمكين الخلفية المتحركة، يرجى تمكين الرسوم المتحركة في الخيارات العامة (مزيد من موارد النظام) أو تغيير صورة الخلفية. - + Session information get failed. فشل الحصول على معلومات الجلسة. - + Telnet - تلنت - - + Telnet تلنت - + Serial - تسلسلي - - + Serial تسلسلي - + Raw - خام - - + Raw خام - + NamePipe - أنبوب الاسم - - + NamePipe أنبوب الاسم - - + + Local Shell الشل المحلي - + Local Shell - الشل المحلي - - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. هذا البرنامج هو محاكي الطرفية الذي يوفر اتصالًا بالشل الآمن (SSH)، واتصالًا بالتلنت، واتصالًا بالمنفذ التسلسلي، ووظائف أخرى. - + This software does not collect any personal information, and does not send any information to the server. هذا البرنامج لا يجمع أي معلومات شخصية، ولا يرسل أي معلومات إلى الخادم. - + This software does not contain any malicious code, and does not contain any backdoors. هذا البرنامج لا يحتوي على أي رمز ضار، ولا يحتوي على أي أبواب خلفية. - + This software is open source software, you can view the source code on the github website. هذا البرنامج هو برنامج مفتوح المصدر، يمكنك عرض الشيفرة المصدرية على موقع github. - + This software is provided as is, without any warranty. يتم توفير هذا البرنامج كما هو، دون أي ضمان. - + If you have any questions or suggestions, please contact the author. إذا كان لديك أي أسئلة أو اقتراحات، يرجى الاتصال بالمؤلف. - + Version الإصدار - + Commit التزام - + Date تاريخ - - + + Author المؤلف - + Are you sure to disconnect " هل أنت متأكد من قطع الاتصال بـ" - + " session? " الجلسة؟ - + Website الموقع الإلكتروني - + Global Shortcuts: اختصارات عامة: - + show/hide menu bar إظهار/إخفاء شريط القائمة - + connect to LocalShell الاتصال بالشل المحلي - + clone current session استنساخ الجلسة الحالية - + switch ui to STD mode تبديل واجهة المستخدم إلى وضع STD - + switch ui to MINI mode تبديل واجهة المستخدم إلى وضع MINI - + switch to previous session التبديل إلى الجلسة السابقة - + switch to next session التبديل إلى الجلسة التالية - + switch to session [num] التبديل إلى الجلسة [رقم] - + Go to line start الانتقال إلى بداية السطر - + Go to line end الانتقال إلى نهاية السطر - + There are sessions that have not yet been unlocked, please unlock them first. هناك جلسات لم يتم فتحها بعد، يرجى فتحها أولاً. - + Are you sure to quit? هل أنت متأكد من الخروج؟ @@ -2707,8 +2708,8 @@ - - + + Warning تحذير @@ -2745,7 +2746,7 @@ If you need to use another shell, please create a session through [quick-connect - + The Default Local Shell is not a valid file! الشل المحلي الافتراضي ليس ملفًا صالحًا! @@ -2795,7 +2796,7 @@ If you need to use another shell, please create a session through [quick-connect نقل - + The User Plugins Path is not a directory! مسار المكونات الإضافية للمستخدم ليس دليلًا! @@ -2869,93 +2870,36 @@ If you need to use another shell, please create a session through [quick-connect الأمر الداخلي - + Copy نسخ - + Paste لصق - + Select All تحديد الكل - + Find بحث - + Zoom In تكبير - + Zoom Out تصغير - - Session - - - Bell in session '%1' - جرس في الجلسة '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - الحجم: XXX x XXX - - - - Size: %1 x %2 - الحجم: %1 x %2 - - - - Paste multiline text - لصق نص متعدد الأسطر - - - - Are you sure you want to paste this text? - هل أنت متأكد من أنك تريد لصق هذا النص؟ - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>تم <a href="http://en.wikipedia.org/wiki/Flow_control">تعليق</a> الإخراج بالضغط على Ctrl+S. اضغط على <b>Ctrl+Q</b> لاستئنافه.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - اتبع الرابط (ctrl + انقر) - - - - Follow path (ctrl + click) - اتبع المسار (ctrl + انقر) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - لا يتوفر مترجم لوحة المفاتيح. المعلومات اللازمة لتحويل ضغطات المفاتيح إلى أحرف لإرسالها إلى الطرفية مفقودة. - - LockSessionWindow @@ -3484,47 +3428,47 @@ If you need to use another shell, please create a session through [quick-connect QObject - + Un-named Color Scheme مخطط ألوان بدون اسم - + Accessible Color Scheme مخطط ألوان قابل للوصول - + Open Link فتح الرابط - + Copy Link Address نسخ عنوان الرابط - + Send Email To... إرسال بريد إلكتروني إلى... - + Copy Email Address نسخ عنوان البريد الإلكتروني - + Open Path فتح المسار - + Open Containing Folder فتح المجلد الذي يحتوي عليه - + Copy Path نسخ المسار @@ -3587,12 +3531,12 @@ If you need to use another shell, please create a session through [quick-connect QTermWidget - + Color Scheme Error خطأ في مخطط الألوان - + Cannot load color scheme: %1 تعذر تحميل مخطط الألوان: %1 @@ -3897,20 +3841,20 @@ If you need to use another shell, please create a session through [quick-connect البحث عن: - - + + Match case حساسية الحالة - - + + Regular expression تعبير منتظم - - + + Highlight all matches تسليط الضوء على جميع النتائج المطابقة @@ -4252,25 +4196,25 @@ If you need to use another shell, please create a session through [quick-connect SessionsWindow - + Telnet Error خطأ في تلنت - + Telnet error: %1. خطأ في تلنت: %1. - - + + Serial Error خطأ في التسلسلي - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ If you need to use another shell, please create a session through [quick-connect %1. - + Raw Socket Error خطأ في المأخذ الخام - + Raw Socket error: %1. خطأ في المأخذ الخام: %1. - + Name Pipe Error خطأ في أنبوب الاسم - + Name Pipe error: %1. خطأ في أنبوب الاسم: %1. - - + + SSH2 Error خطأ في SSH2 - - + + SSH2 error: %1. خطأ في SSH2: %1. - - + + Open URL فتح الرابط - - + + Cannot open URL %1. تعذر فتح الرابط %1. - + Select Files to Send using Zmodem حدد الملفات لإرسالها باستخدام Zmodem - + All Files (*) كل الملفات (*) - + Start Local Shell بدء الشل المحلي - + Cannot start local shell: %1. تعذر بدء الشل المحلي: %1. - + Serial port %1 has been removed. تمت إزالة المنفذ التسلسلي %1. - + Save log... حفظ السجل... - + log files (*.log) ملفات السجل (*.log) - + Save log حفظ السجل - - - + + + Cannot write file %1: %2. تعذر كتابة الملف %1: %2. - + Save Raw log... حفظ السجل الخام... - + binary files (*.bin) ملفات البيانات الثنائية (*.bin) - + Save Raw log حفظ السجل الخام - + Unlock Session فتح الجلسة - + Wrong password! كلمة مرور خاطئة! - + Receive ASCII File استقبال ملف ASCII @@ -4662,6 +4606,34 @@ If you need to use another shell, please create a session through [quick-connect معلومات النقل + + TerminalDisplay + + + Size: XXX x XXX + الحجم: XXX x XXX + + + + Size: %1 x %2 + الحجم: %1 x %2 + + + + Paste multiline text + لصق نص متعدد الأسطر + + + + Are you sure you want to paste this text? + هل أنت متأكد من أنك تريد لصق هذا النص؟ + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>تم <a href="http://en.wikipedia.org/wiki/Flow_control">تعليق</a> الإخراج بالضغط على Ctrl+S. اضغط على <b>Ctrl+Q</b> لاستئنافه.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ If you need to use another shell, please create a session through [quick-connect الكتابة فوق %1 حرفًا + + UrlFilter + + + Follow link (ctrl + click) + اتبع الرابط (ctrl + انقر) + + + + Follow path (ctrl + click) + اتبع المسار (ctrl + انقر) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + لا يتوفر مترجم لوحة المفاتيح. المعلومات اللازمة لتحويل ضغطات المفاتيح إلى أحرف لإرسالها إلى الطرفية مفقودة. + + keyMapManager diff --git a/lang/quardCRT_cs_CZ.ts b/lang/quardCRT_cs_CZ.ts index d124b968..0c566333 100644 --- a/lang/quardCRT_cs_CZ.ts +++ b/lang/quardCRT_cs_CZ.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Nástrojová lišta @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Varování @@ -285,7 +285,7 @@ - + Ready Připraveno @@ -464,7 +464,7 @@ - + Help Nápověda @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Zadejte hosta <Alt+R> pro připojení - + Disconnect All Odpojit všechny - + Disconnect all sessions Odpojit všechny relace - + Clone Session Klonovat relaci - + Clone current session <Ctrl+Shift+T> Klonovat aktuální relaci <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Zamknout relaci - + Log Session Logovat relaci - + Create a log file for current session Vytvořit logovací soubor pro aktuální relaci - + Raw Log Session Raw logovací relace - + Create a raw log file for current session Vytvořit raw logovací soubor pro aktuální relaci - + Hex View Hex zobrazení - + Show/Hide Hex View for current session Zobrazit/Skrýt Hex zobrazení pro aktuální relaci - + Exit Ukončit - + Quit the application Ukončit aplikaci - + Copy Kopírovat - + Copy the selected text to the clipboard <Command+C> Kopírovat vybraný text do schránky <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Kopírovat vybraný text do schránky <Ctrl+Ins> - + Paste Vložit - + Paste the clipboard text to the current session <Command+V> Vložit text ze schránky do aktuální relace <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Vložit text ze schránky do aktuální relace <Shift+Ins> - + Copy and Paste Kopírovat a vložit - + Copy the selected text to the clipboard and paste to the current session Kopírovat vybraný text do schránky a vložit do aktuální relace - + Select All Vybrat vše - + Select all text in the current session <Ctrl+Shift+A> Vybrat všechny text v aktuální relaci <Ctrl+Shift+A> - + Find... Hledat... - + Find text in the current session <Ctrl+F> Hledat text v aktuální relaci <Ctrl+F> - + Print Screen Tisk obrazovky - + Print current screen Tisk aktuální obrazovky - + Screen Shot Snímek obrazovky - + Screen shot current screen <Alt+P> Snímek obrazovky aktuální obrazovky <Alt+P> - + Session Export Export relace - + Export current session to a file <Alt+O> Exportovat aktuální relaci do souboru <Alt+O> - + Clear Scrollback Vymazat posuvník - + Clear the contents of the scrollback rows Vymazat obsah řádků posuvníku - + Clear Screen Vymazat obrazovku - + Clear the contents of the current screen Vymazat obsah aktuální obrazovky - + Clear Screen and Scrollback Vymazat obrazovku a posuvník - + Clear the contents of the screen and scrollback Vymazat obsah obrazovky a posuvníku - + Reset Resetovat - + Reset terminal emulator Resetovat emulátor terminálu - + Zoom In Přiblížit - + Zoom In <Ctrl+"="> Přiblížit <Ctrl+"="> - + Zoom Out Oddálit - + Zoom Out <Ctrl+"-"> Oddálit <Ctrl+"-"> - - + + Zoom Reset Resetovat přiblížení - + Layout Rozložení - + Single Layout Jednoduché rozložení - + Single layout Jednoduché rozložení - + Two Columns Layout Dvou sloupcové rozložení - + Two columns layout Dvou sloupcové rozložení - + Three Columns Layout Tří sloupcové rozložení - + Three columns layout Tří sloupcové rozložení - + Two Rows Layout Dvou řádkové rozložení - + Two rows layout Dvou řádkové rozložení - + Three Rows Layout Tří řádkové rozložení - + Three rows layout Tří řádkové rozložení - + Grid Layout Rozložení mřížky - + Grid layout Rozložení mřížky - + Two Rows Right Layout Dvou řádkové pravé rozložení - + Two rows right layout Dvou řádkové pravé rozložení - + Two Columns Bottom Layout Dvou sloupcové dolní rozložení - + Two columns bottom layout Dvou sloupcové dolní rozložení - + Flip Layout Překlopit rozložení - + Flip layout Překlopit rozložení - + Menu Bar Menu lišta - + Show/Hide Menu Bar <Alt+U> Zobrazit/Skrýt Menu lištu <Alt+U> - + Show/Hide Tool Bar Zobrazit/Skrýt Nástrojovou lištu - + Status Bar Stavová lišta - + Show/Hide Status Bar Zobrazit/Skrýt Stavovou lištu - + Command Window Okno příkazů - + Show/Hide Command Window Zobrazit/Skrýt Okno příkazů - + Connect Bar Připojovací lišta - + Show/Hide Connect Bar Zobrazit/Skrýt Připojovací lištu - + Side Window Boční okno - + Show/Hide Side Window Zobrazit/Skrýt Boční okno - + Windows Transparency Průhlednost oken - + Enable/Disable alpha transparency Povolit/Zakázat alfa průhlednost - + Vertical Scroll Bar Vertikální posuvník - + Show/Hide Vertical Scroll Bar Zobrazit/Skrýt Vertikální posuvník - + Allways On Top Vždy nahoře - + Show window always on top Zobrazit okno vždy nahoře - + Full Screen Na celou obrazovku - + Toggle between full screen and normal mode <Alt+Enter> Přepnout mezi režimem na celou obrazovku a normálním režimem <Alt+Enter> - + Session Options... Možnosti relace... - + Configure session options Nastavit možnosti relace - + Global Options... Globální možnosti... - + Configure global options Nastavit globální možnosti - + Real-time Save Options Možnosti ukládání v reálném čase - + Real-time save session options and global options Možnosti ukládání relace a globální možnosti v reálném čase - + Save Settings Now Uložit nastavení nyní - + Save options configuration now Uložit konfiguraci možností nyní - + Send ASCII... Odeslat ASCII... - + Send ASCII file Odeslat ASCII soubor - + Receive ASCII... Přijmout ASCII... - + Receive ASCII file Přijmout ASCII soubor - + Send Binary... Odeslat binárně... - + Send Binary file Odeslat binární soubor - + Send Kermit... Odeslat Kermit... - + Send a file using Kermit Odeslat soubor pomocí Kermitu - + Receive Kermit... Přijmout Kermit... - + Receive a file using Kermit Přijmout soubor pomocí Kermitu - + Send Xmodem... Odeslat Xmodem... - + Send a file using Xmodem Odeslat soubor pomocí Xmodemu - + Receive Xmodem... Přijmout Xmodem... - + Receive a file using Xmodem Přijmout soubor pomocí Xmodemu - + Send Ymodem... Odeslat Ymodem... - + Send a file using Ymodem Odeslat soubor pomocí Ymodemu - + Receive Ymodem... Přijmout Ymodem... - + Receive a file using Ymodem Přijmout soubor pomocí Ymodemu - + Zmodem Upload List... Seznam nahrávání Zmodemu... - + Display Zmodem file upload list Zobrazit seznam nahrávání souborů Zmodemu - + Start Zmodem Upload Spustit nahrávání Zmodemu - + Start Zmodem file upload Spustit nahrávání souboru Zmodemu - + Start TFTP Server Spustit TFTP server - + Start/Stop the TFTP server Spustit/Zastavit TFTP server - + Run... Spustit... - + Run a script Spustit skript - + Cancel Zrušit @@ -1213,759 +1214,759 @@ Změnit barvu - + Cancel script execution Zrušit spuštění skriptu - + Start Recording Script Začít nahrávat skript - + Start recording script Začít nahrávat skript - + Stop Recording Script... Zastavit nahrávání skriptu... - + Stop recording script Zastavit nahrávání skriptu - + Cancel Recording Script Zrušit nahrávání skriptu - + Cancel recording script Zrušit nahrávání skriptu - + Add Bookmark Přidat záložku - + Add a bookmark Přidat záložku - - + + Remove Bookmark Odstranit záložku - + Remove a bookmark Odstranit záložku - - + + Clean All Bookmark Vymazat všechny záložky - + Clean all bookmark Vymazat všechny záložky - + Keymap Manager Manažer klávesových zkratek - + Display keymap editor Zobrazit editor klávesových zkratek - + Create Public Key... Vytvořit veřejný klíč... - + Create a public key Vytvořit veřejný klíč - + Publickey Manager Manažer veřejných klíčů - + Display publickey manager Zobrazit manažer veřejných klíčů - + Internal Command Interní příkaz - + Display Internal Command window Zobrazit okno interního příkazu - + Tab Záložka - + Arrange sessions in tabs Uspořádat relace do záložek - + Tile Dlaždice - + Arrange sessions in non-overlapping tiles Uspořádat relace do nestínajících se dlaždic - + Cascade Kaskáda - + Arrange sessions to overlap each other Uspořádat relace tak, aby se překrývaly - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Light Lehký - + Switch to light theme Přepnout na světlé téma - + Dark Tmavý - + Switch to dark theme Přepnout na tmavé téma - + Theme Color Barva tématu - + Set theme color, cancel to use default Nastavit barvu tématu, zrušit pro použití výchozí - + Display help Zobrazit nápovědu - - + + Keyborad Shortcuts Reference Reference klávesových zkratek - + Display keyborad shortcuts reference Zobrazit referenci klávesových zkratek - + Check Update Zkontrolovat aktualizaci - + Check for updates Zkontrolovat aktualizace - - + + Privacy Statement Prohlášení o ochraně osobních údajů - + Display privacy statement Zobrazit prohlášení o ochraně osobních údajů - - + + About O programu - + Display about dialog Zobrazit dialog O programu - + About Qt O Qt - + Display about Qt dialog Zobrazit dialog O Qt - - + + About Python O Pythonu - + Display about Python dialog Zobrazit dialog O Pythonu - + Laboratory Laboratoř - - + + SSH Scanning SSH skenování - + Display SSH scanning dialog Zobrazit dialog SSH skenování - + Plugin Info Informace o pluginu - + Display plugin information dialog Zobrazit dialog s informacemi o pluginu - + Plugin metaData not found! Metadata pluginu nebyla nalezena! - + Plugin api version not found! Verze API pluginu nebyla nalezena! - + Plugin api version not match! Verze API pluginu neodpovídá! - + Plugin menu not found! Menu pluginu nebylo nalezeno! - + Plugin init failed! Spouštění pluginu se nezdařilo! - + PrintScreen saved to %1 Tisk obrazovky uložen do %1 - + Save Screenshot Uložit snímek obrazovky - + Image Files (*.jpg) Obrázkové soubory (*.jpg) - - + + Screenshot saved to %1 Snímek obrazovky uložen do %1 - + Save Session Export Uložit export relace - + Text Files (*.txt);;HTML Files (*.html) Textové soubory (*.txt);;HTML soubory (*.html) - + Text Files (*.txt) Textové soubory (*.txt) - + HTML Files (*.html) HTML soubory (*.html) - + Session Export saved to %1 Export relace uložen do %1 - + Session Export failed to save to %1 Export relace se nepodařilo uložit do %1 - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! Relace vysílání nemůže přenášet soubory! - + Select Files to Send as ASCII Vybrat soubory k odeslání jako ASCII - - + + Text Files (*.txt);;All Files (*) Textové soubory (*.txt);;Všechny soubory (*) - + Save Received Data as ASCII Uložit přijatá data jako ASCII - + Select Files to Send as BINARY Vybrat soubory k odeslání jako BINÁRNÍ - - - - - - + + + + + + All Files (*) Všechny soubory (*) - + Select Files to Send using Kermit Vybrat soubory k odeslání pomocí Kermitu - + Select Files to Send using Xmodem Vybrat soubory k odeslání pomocí Xmodemu - + Save Received Files using Xmodem Uložit přijaté soubory pomocí Xmodemu - + Select Files to Send using Ymodem Vybrat soubory k odeslání pomocí Ymodemu - + Select Files to Send using Zmodem Vybrat soubory k odeslání pomocí Zmodemu - + Select a script file Vybrat soubor skriptu - + Python Files (*.py);;All Files (*) Python soubory (*.py);;Všechny soubory (*) - + Select a directory Vybrat adresář - + Select a bookmark Vybrat záložku - + Are you sure to clean all bookmark? Opravdu chcete vymazat všechny záložky? - + Port Port - + Select color Vybrat barvu - + Video background is enabled, please enable animation in global options (more system resources) or change background image. Video pozadí je povoleno, povolte animaci v globálních možnostech (více systémových prostředků) nebo změňte obrázek pozadí. - + Session information get failed. Načtení informací o relaci se nezdařilo. - + Telnet - Telnet - - + Telnet Telnet - + Serial - Sériový port - - + Serial Sériový port - + Raw - Raw - - + Raw Raw - + NamePipe - NamePipe - - + NamePipe NamePipe - - + + Local Shell Lokální shell - + Local Shell - Lokální shell - - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Tento software je emulátor terminálu, který poskytuje zabezpečené připojení shellu (SSH), připojení telnetu, připojení sériového portu a další funkce. - + This software does not collect any personal information, and does not send any information to the server. Tento software nezískává žádné osobní údaje a neodesílá žádné informace na server. - + This software does not contain any malicious code, and does not contain any backdoors. Tento software neobsahuje žádný škodlivý kód a neobsahuje žádné zadní vrátka. - + This software is open source software, you can view the source code on the github website. Tento software je open source software, zdrojový kód můžete zobrazit na webové stránce github. - + This software is provided as is, without any warranty. Tento software je poskytován tak, jak je, bez jakékoli záruky. - + If you have any questions or suggestions, please contact the author. Pokud máte nějaké dotazy nebo návrhy, kontaktujte autora. - + Version Verze - + Commit Commit - + Date Datum - - + + Author Autor - + Are you sure to disconnect " Opravdu chcete odpojit " - + " session? " relaci? - + Website Webová stránka - + Global Shortcuts: Globální klávesové zkratky: - + show/hide menu bar zobrazit/skrýt menu - + connect to LocalShell připojit k lokálnímu shellu - + clone current session klonovat aktuální relaci - + switch ui to STD mode přepnout UI do STD režimu - + switch ui to MINI mode přepnout UI do MINI režimu - + switch to previous session přepnout na předchozí relaci - + switch to next session přepnout na další relaci - + switch to session [num] přepnout na relaci [číslo] - + Go to line start Jít na začátek řádku - + Go to line end Jít na konec řádku - + There are sessions that have not yet been unlocked, please unlock them first. Existují relace, které ještě nebyly odemčeny, nejprve je odemkněte. - + Are you sure to quit? Opravdu chcete skončit? @@ -2707,8 +2708,8 @@ - - + + Warning Varování @@ -2745,7 +2746,7 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv - + The Default Local Shell is not a valid file! Výchozí lokální shell není platný soubor! @@ -2795,7 +2796,7 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv Přenos - + The User Plugins Path is not a directory! Cesta k uživatelským pluginům není adresářem! @@ -2869,93 +2870,36 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv Vnitřní příkaz - + Copy Kopírovat - + Paste Vložit - + Select All Vybrat vše - + Find Najít - + Zoom In Přiblížit - + Zoom Out Oddálit - - Session - - - Bell in session '%1' - Zvonek v relaci '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Velikost: XXX x XXX - - - - Size: %1 x %2 - Velikost: %1 x %2 - - - - Paste multiline text - Vložit víceřádkový text - - - - Are you sure you want to paste this text? - Opravdu chcete tento text vložit? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>Výstup byl <a href="http://en.wikipedia.org/wiki/Flow_control">přerušen</a> stisknutím Ctrl+S. Stiskněte <b>Ctrl+Q</b> pro obnovení.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Následovat odkaz (ctrl + kliknutí) - - - - Follow path (ctrl + click) - Následovat cestu (ctrl + kliknutí) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - Není k dispozici žádný překladač klávesnice. Chybí informace potřebné k převodu stisknutí kláves na znaky k odeslání do terminálu. - - LockSessionWindow @@ -3484,47 +3428,47 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv QObject - + Un-named Color Scheme Nepojmenovaný barevný schéma - + Accessible Color Scheme Přístupné barevné schéma - + Open Link Otevřít odkaz - + Copy Link Address Kopírovat adresu odkazu - + Send Email To... Odeslat e-mail na... - + Copy Email Address Kopírovat e-mailovou adresu - + Open Path Otevřít cestu - + Open Containing Folder Otevřít obsahující složku - + Copy Path Kopírovat cestu @@ -3587,12 +3531,12 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv QTermWidget - + Color Scheme Error Chyba barevného schématu - + Cannot load color scheme: %1 Nelze načíst barevné schéma: %1 @@ -3897,20 +3841,20 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv Najít: - - + + Match case Rozlišovat velikost písmen - - + + Regular expression Regulární výraz - - + + Highlight all matches Zvýraznit všechny shody @@ -4252,25 +4196,25 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv SessionsWindow - + Telnet Error Chyba Telnetu - + Telnet error: %1. Chyba Telnetu: %1. - - + + Serial Error Chyba sériového portu - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv %1. - + Raw Socket Error Chyba Raw Socketu - + Raw Socket error: %1. Chyba Raw Socketu: %1. - + Name Pipe Error Chyba pojmenované roury - + Name Pipe error: %1. Chyba pojmenované roury: %1. - - + + SSH2 Error Chyba SSH2 - - + + SSH2 error: %1. Chyba SSH2: %1. - - + + Open URL Otevřít URL - - + + Cannot open URL %1. Nelze otevřít URL %1. - + Select Files to Send using Zmodem Vybrat soubory k odeslání pomocí Zmodemu - + All Files (*) Všechny soubory (*) - + Start Local Shell Spustit lokální shell - + Cannot start local shell: %1. Nelze spustit lokální shell: %1. - + Serial port %1 has been removed. Sériový port %1 byl odstraněn. - + Save log... Uložit log... - + log files (*.log) logovací soubory (*.log) - + Save log Uložit log - - - + + + Cannot write file %1: %2. Nelze zapsat soubor %1: %2. - + Save Raw log... Uložit Raw log... - + binary files (*.bin) binární soubory (*.bin) - + Save Raw log Uložit Raw log - + Unlock Session Odemknout relaci - + Wrong password! Špatné heslo! - + Receive ASCII File Přijmout ASCII soubor @@ -4662,6 +4606,34 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv Informace o přenosu + + TerminalDisplay + + + Size: XXX x XXX + Velikost: XXX x XXX + + + + Size: %1 x %2 + Velikost: %1 x %2 + + + + Paste multiline text + Vložit víceřádkový text + + + + Are you sure you want to paste this text? + Opravdu chcete tento text vložit? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Výstup byl <a href="http://en.wikipedia.org/wiki/Flow_control">přerušen</a> stisknutím Ctrl+S. Stiskněte <b>Ctrl+Q</b> pro obnovení.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ Pokud potřebujete použít jiný shell, vytvořte prosím relaci prostřednictv Přepsat %1 znaků + + UrlFilter + + + Follow link (ctrl + click) + Následovat odkaz (ctrl + kliknutí) + + + + Follow path (ctrl + click) + Následovat cestu (ctrl + kliknutí) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Není k dispozici žádný překladač klávesnice. Chybí informace potřebné k převodu stisknutí kláves na znaky k odeslání do terminálu. + + keyMapManager diff --git a/lang/quardCRT_de_DE.ts b/lang/quardCRT_de_DE.ts index 3ca56e17..2ddfb9f8 100644 --- a/lang/quardCRT_de_DE.ts +++ b/lang/quardCRT_de_DE.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Werkzeugleiste @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Warnung @@ -285,7 +285,7 @@ - + Ready Bereit @@ -464,7 +464,7 @@ - + Help Hilfe @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Geben Sie <Alt+R> ein, um eine Verbindung zum Host herzustellen - + Disconnect All Alle trennen - + Disconnect all sessions Alle Sitzungen trennen - + Clone Session Sitzung klonen - + Clone current session <Ctrl+Shift+T> Aktuelle Sitzung klonen <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Sitzung sperren - + Log Session Sitzung protokollieren - + Create a log file for current session Erstellen Sie eine Protokolldatei für die aktuelle Sitzung - + Raw Log Session Raw-Log-Sitzung - + Create a raw log file for current session Erstellen Sie eine Raw-Protokolldatei für die aktuelle Sitzung - + Hex View Hex-Ansicht - + Show/Hide Hex View for current session Hex-Ansicht für aktuelle Sitzung anzeigen/ausblenden - + Exit Beenden - + Quit the application Beenden Sie die Anwendung - + Copy Kopieren - + Copy the selected text to the clipboard <Command+C> Kopieren Sie den ausgewählten Text in die Zwischenablage <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Kopieren Sie den ausgewählten Text in die Zwischenablage <Ctrl+Ins> - + Paste Einfügen - + Paste the clipboard text to the current session <Command+V> Fügen Sie den Zwischenablage-Text in die aktuelle Sitzung ein <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Fügen Sie den Zwischenablage-Text in die aktuelle Sitzung ein <Shift+Ins> - + Copy and Paste Kopieren und Einfügen - + Copy the selected text to the clipboard and paste to the current session Kopieren Sie den ausgewählten Text in die Zwischenablage und fügen Sie ihn in die aktuelle Sitzung ein - + Select All Alles auswählen - + Select all text in the current session <Ctrl+Shift+A> Wählen Sie den gesamten Text in der aktuellen Sitzung aus <Ctrl+Shift+A> - + Find... Suchen... - + Find text in the current session <Ctrl+F> Suchen Sie Text in der aktuellen Sitzung <Ctrl+F> - + Print Screen Bildschirm drucken - + Print current screen Aktuellen Bildschirm drucken - + Screen Shot Bildschirmfoto - + Screen shot current screen <Alt+P> Aktuellen Bildschirmfoto <Alt+P> - + Session Export Sitzung exportieren - + Export current session to a file <Alt+O> Aktuelle Sitzung in eine Datei exportieren <Alt+O> - + Clear Scrollback Scrollback löschen - + Clear the contents of the scrollback rows Löschen Sie den Inhalt der Scrollback-Reihen aus - + Clear Screen Bildschirm löschen - + Clear the contents of the current screen Löschen Sie den Inhalt des aktuellen Bildschirms - + Clear Screen and Scrollback Bildschirm und Scrollback löschen - + Clear the contents of the screen and scrollback Löschen Sie den Inhalt des Bildschirms und des Scrollback - + Reset Zurücksetzen - + Reset terminal emulator Terminal-Emulator zurücksetzen - + Zoom In Vergrößern - + Zoom In <Ctrl+"="> Vergrößern <Ctrl+"="> - + Zoom Out Verkleinern - + Zoom Out <Ctrl+"-"> Verkleinern <Ctrl+"-"> - - + + Zoom Reset Zoom zurücksetzen - + Layout Layout - + Single Layout Einzelnes Layout - + Single layout Einzelnes Layout - + Two Columns Layout Zwei Spalten Layout - + Two columns layout Zwei Spalten Layout - + Three Columns Layout Drei Spalten Layout - + Three columns layout Drei Spalten Layout - + Two Rows Layout Zwei Reihen Layout - + Two rows layout Zwei Reihen Layout - + Three Rows Layout Drei Reihen Layout - + Three rows layout Drei Reihen Layout - + Grid Layout Rasterlayout - + Grid layout Rasterlayout - + Two Rows Right Layout Zwei Reihen rechts Layout - + Two rows right layout Zwei Reihen rechts Layout - + Two Columns Bottom Layout Zwei Spalten unten Layout - + Two columns bottom layout Zwei Spalten unten Layout - + Flip Layout Layout umdrehen - + Flip layout Layout umdrehen - + Menu Bar Menüleiste - + Show/Hide Menu Bar <Alt+U> Menüleiste anzeigen/ausblenden <Alt+U> - + Show/Hide Tool Bar Werkzeugleiste anzeigen/ausblenden - + Status Bar Statusleiste - + Show/Hide Status Bar Statusleiste anzeigen/ausblenden - + Command Window Befehlsfenster - + Show/Hide Command Window Befehlsfenster anzeigen/ausblenden - + Connect Bar Verbindungsleiste - + Show/Hide Connect Bar Verbindungsleiste anzeigen/ausblenden - + Side Window Seitenfenster - + Show/Hide Side Window Seitenfenster anzeigen/ausblenden - + Windows Transparency Windows-Transparenz - + Enable/Disable alpha transparency Alpha-Transparenz aktivieren/deaktivieren - + Vertical Scroll Bar Vertikale Bildlaufleiste - + Show/Hide Vertical Scroll Bar Vertikale Bildlaufleiste anzeigen/ausblenden - + Allways On Top Immer im Vordergrund - + Show window always on top Fenster immer im Vordergrund anzeigen - + Full Screen Vollbildmodus - + Toggle between full screen and normal mode <Alt+Enter> Wechseln Sie zwischen Vollbild- und Normalmodus <Alt+Enter> - + Session Options... Sitzungsoptionen... - + Configure session options Sitzungsoptionen konfigurieren - + Global Options... Globale Optionen... - + Configure global options Globale Optionen konfigurieren - + Real-time Save Options Optionen in Echtzeit speichern - + Real-time save session options and global options Sitzungsoptionen und globale Optionen in Echtzeit speichern - + Save Settings Now Einstellungen jetzt speichern - + Save options configuration now Speichern Sie die Optionenkonfiguration jetzt - + Send ASCII... ASCII senden... - + Send ASCII file ASCII-Datei senden - + Receive ASCII... ASCII empfangen... - + Receive ASCII file ASCII-Datei empfangen - + Send Binary... Binär senden... - + Send Binary file Binärdatei senden - + Send Kermit... Kermit senden... - + Send a file using Kermit Senden Sie eine Datei mit Kermit - + Receive Kermit... Kermit empfangen... - + Receive a file using Kermit Empfangen Sie eine Datei mit Kermit - + Send Xmodem... Xmodem senden... - + Send a file using Xmodem Senden Sie eine Datei mit Xmodem - + Receive Xmodem... Xmodem empfangen... - + Receive a file using Xmodem Empfangen Sie eine Datei mit Xmodem - + Send Ymodem... Ymodem senden... - + Send a file using Ymodem Senden Sie eine Datei mit Ymodem - + Receive Ymodem... Ymodem empfangen... - + Receive a file using Ymodem Empfangen Sie eine Datei mit Ymodem - + Zmodem Upload List... Zmodem-Upload-Liste... - + Display Zmodem file upload list Zmodem-Datei-Upload-Liste anzeigen - + Start Zmodem Upload Zmodem-Upload starten - + Start Zmodem file upload Zmodem-Datei-Upload starten - + Start TFTP Server TFTP-Server starten - + Start/Stop the TFTP server Starten/Stoppen Sie den TFTP-Server - + Run... Ausführen... - + Run a script Führen Sie ein Skript aus - + Cancel Abbrechen @@ -1213,759 +1214,759 @@ Farbe ändern - + Cancel script execution Skriptausführung abbrechen - + Start Recording Script Skriptaufzeichnung starten - + Start recording script Starten Sie die Skriptaufzeichnung - + Stop Recording Script... Skriptaufzeichnung beenden... - + Stop recording script Beenden Sie die Skriptaufzeichnung - + Cancel Recording Script Skriptaufzeichnung abbrechen - + Cancel recording script Skriptaufzeichnung abbrechen - + Add Bookmark Lesezeichen hinzufügen - + Add a bookmark Fügen Sie ein Lesezeichen hinzu - - + + Remove Bookmark Lesezeichen entfernen - + Remove a bookmark Entfernen Sie ein Lesezeichen - - + + Clean All Bookmark Alle Lesezeichen löschen - + Clean all bookmark Löschen Sie alle Lesezeichen - + Keymap Manager Tastaturbelegungs-Manager - + Display keymap editor Tastaturbelegungs-Editor anzeigen - + Create Public Key... Öffentlichen Schlüssel erstellen... - + Create a public key Erstellen Sie einen öffentlichen Schlüssel - + Publickey Manager Öffentlicher Schlüssel-Manager - + Display publickey manager Öffentlichen Schlüssel-Manager anzeigen - + Internal Command Interner Befehl - + Display Internal Command window Interner Befehlsfenster anzeigen - + Tab Tab - + Arrange sessions in tabs Ordnen Sie Sitzungen in Tabs an - + Tile Fliese - + Arrange sessions in non-overlapping tiles Ordnen Sie Sitzungen in nicht überlappenden Kacheln an - + Cascade Kaskade - + Arrange sessions to overlap each other Ordnen Sie Sitzungen so an, dass sie sich überlappen - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Light Leicht - + Switch to light theme Wechseln Sie zum hellen Thema - + Dark Dunkel - + Switch to dark theme Wechseln Sie zum dunklen Thema - + Theme Color Themenfarbe - + Set theme color, cancel to use default Themenfarbe festlegen, Abbrechen, um die Standardeinstellung zu verwenden - + Display help Hilfe anzeigen - - + + Keyborad Shortcuts Reference Tastaturkürzel-Referenz - + Display keyborad shortcuts reference Tastaturkürzel-Referenz anzeigen - + Check Update Update überprüfen - + Check for updates Suche nach Updates - - + + Privacy Statement Datenschutzerklärung - + Display privacy statement Datenschutzerklärung anzeigen - - + + About Über - + Display about dialog Über Dialog anzeigen - + About Qt Über Qt - + Display about Qt dialog Über Qt-Dialog anzeigen - - + + About Python Über Python - + Display about Python dialog Über Python-Dialog anzeigen - + Laboratory Labor - - + + SSH Scanning SSH-Scannen - + Display SSH scanning dialog SSH-Scannen-Dialog anzeigen - + Plugin Info Plugin-Info - + Display plugin information dialog Plugin-Informationen anzeigen - + Plugin metaData not found! Plugin-Metadaten nicht gefunden! - + Plugin api version not found! Plugin-API-Version nicht gefunden! - + Plugin api version not match! Plugin-API-Version stimmt nicht überein! - + Plugin menu not found! Plugin-Menü nicht gefunden! - + Plugin init failed! Plugin-Initialisierung fehlgeschlagen! - + PrintScreen saved to %1 PrintScreen gespeichert unter %1 - + Save Screenshot Bildschirmfoto speichern - + Image Files (*.jpg) Bilddateien (*.jpg) - - + + Screenshot saved to %1 Bildschirmfoto gespeichert unter %1 - + Save Session Export Sitzungsexport speichern - + Text Files (*.txt);;HTML Files (*.html) Textdateien (*.txt);;HTML-Dateien (*.html) - + Text Files (*.txt) Textdateien (*.txt) - + HTML Files (*.html) HTML-Dateien (*.html) - + Session Export saved to %1 Sitzungsexport gespeichert unter %1 - + Session Export failed to save to %1 Sitzungsexport konnte nicht unter %1 gespeichert werden - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! Die Broadcast-Sitzung kann keine Datei übertragen! - + Select Files to Send as ASCII Wählen Sie Dateien aus, die als ASCII gesendet werden sollen - - + + Text Files (*.txt);;All Files (*) Textdateien (*.txt);;Alle Dateien (*) - + Save Received Data as ASCII Empfangene Daten als ASCII speichern - + Select Files to Send as BINARY Wählen Sie Dateien aus, die als BINÄR gesendet werden sollen - - - - - - + + + + + + All Files (*) Alle Dateien (*) - + Select Files to Send using Kermit Wählen Sie Dateien aus, die mit Kermit gesendet werden sollen - + Select Files to Send using Xmodem Wählen Sie Dateien aus, die mit Xmodem gesendet werden sollen - + Save Received Files using Xmodem Empfangene Dateien mit Xmodem speichern - + Select Files to Send using Ymodem Wählen Sie Dateien aus, die mit Ymodem gesendet werden sollen - + Select Files to Send using Zmodem Wählen Sie Dateien aus, die mit Zmodem gesendet werden sollen - + Select a script file Wählen Sie eine Skriptdatei aus - + Python Files (*.py);;All Files (*) Python-Dateien (*.py);;Alle Dateien (*) - + Select a directory Wählen Sie ein Verzeichnis aus - + Select a bookmark Wählen Sie ein Lesezeichen aus - + Are you sure to clean all bookmark? Möchten Sie wirklich alle Lesezeichen löschen? - + Port Port - + Select color Farbe auswählen - + Video background is enabled, please enable animation in global options (more system resources) or change background image. Das Videohintergrund ist aktiviert. Aktivieren Sie die Animation in den globalen Optionen (mehr Systemressourcen) oder ändern Sie das Hintergrundbild. - + Session information get failed. Sitzungsinformationen konnten nicht abgerufen werden. - + Telnet - Telnet - - + Telnet Telnet - + Serial - Seriell - - + Serial Seriell - + Raw - Raw - - + Raw Raw - + NamePipe - NamePipe - - + NamePipe NamePipe - - + + Local Shell Lokale Shell - + Local Shell - Lokale Shell - - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Diese Software ist ein Terminal-Emulator, der eine sichere Shell (SSH)-Verbindung, eine Telnet-Verbindung, eine serielle Port-Verbindung und andere Funktionen bereitstellt. - + This software does not collect any personal information, and does not send any information to the server. Diese Software sammelt keine persönlichen Informationen und sendet keine Informationen an den Server. - + This software does not contain any malicious code, and does not contain any backdoors. Diese Software enthält keinen bösartigen Code und enthält keine Hintertüren. - + This software is open source software, you can view the source code on the github website. Diese Software ist Open-Source-Software. Sie können den Quellcode auf der GitHub-Website einsehen. - + This software is provided as is, without any warranty. Diese Software wird wie sie ist, ohne jegliche Garantie, bereitgestellt. - + If you have any questions or suggestions, please contact the author. Wenn Sie Fragen oder Anregungen haben, wenden Sie sich bitte an den Autor. - + Version Version - + Commit Commit - + Date Datum - - + + Author Autor - + Are you sure to disconnect " Möchten Sie wirklich die Verbindung trennen " - + " session? " Sitzung? - + Website Webseite - + Global Shortcuts: Globale Tastenkombinationen: - + show/hide menu bar Menüleiste anzeigen/ausblenden - + connect to LocalShell Mit LocalShell verbinden - + clone current session Aktuelle Sitzung klonen - + switch ui to STD mode UI in den STD-Modus umschalten - + switch ui to MINI mode UI in den MINI-Modus umschalten - + switch to previous session Zur vorherigen Sitzung wechseln - + switch to next session Zur nächsten Sitzung wechseln - + switch to session [num] Zur Sitzung [Nummer] wechseln - + Go to line start Zur Zeilenanfang gehen - + Go to line end Zum Zeilenende gehen - + There are sessions that have not yet been unlocked, please unlock them first. Es gibt Sitzungen, die noch nicht entsperrt wurden. Bitte entsperren Sie sie zuerst. - + Are you sure to quit? Möchten Sie wirklich beenden? @@ -2707,8 +2708,8 @@ - - + + Warning Warnung @@ -2745,7 +2746,7 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung - + The Default Local Shell is not a valid file! Die Standard-Local-Shell ist keine gültige Datei! @@ -2795,7 +2796,7 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung Übertragen - + The User Plugins Path is not a directory! Der Benutzer-Plugins-Pfad ist kein Verzeichnis! @@ -2869,93 +2870,36 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung Interner Befehl - + Copy Kopieren - + Paste Einfügen - + Select All Alles auswählen - + Find Suchen - + Zoom In Vergrößern - + Zoom Out Verkleinern - - Session - - - Bell in session '%1' - Signalton in Sitzung '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Größe: XXX x XXX - - - - Size: %1 x %2 - Größe: %1 x %2 - - - - Paste multiline text - Mehrzeiligen Text einfügen - - - - Are you sure you want to paste this text? - Möchten Sie diesen Text wirklich einfügen? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>Die Ausgabe wurde durch Drücken von Strg+S <a href="http://en.wikipedia.org/wiki/Flow_control">angehalten</a>. Drücken Sie <b>Strg+Q</b>, um fortzufahren.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Link folgen (Strg + Klick) - - - - Follow path (ctrl + click) - Pfad folgen (Strg + Klick) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - Kein Tastaturübersetzer verfügbar. Die Informationen, die zum Konvertieren von Tastendrücken in Zeichen, die an das Terminal gesendet werden sollen, fehlen. - - LockSessionWindow @@ -3484,47 +3428,47 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung QObject - + Un-named Color Scheme Unbenanntes Farbschema - + Accessible Color Scheme Zugängliches Farbschema - + Open Link Link öffnen - + Copy Link Address Link-Adresse kopieren - + Send Email To... E-Mail senden an... - + Copy Email Address E-Mail-Adresse kopieren - + Open Path Pfad öffnen - + Open Containing Folder Übergeordneten Ordner öffnen - + Copy Path Pfad kopieren @@ -3587,12 +3531,12 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung QTermWidget - + Color Scheme Error Farbschema-Fehler - + Cannot load color scheme: %1 Farbschema kann nicht geladen werden: %1 @@ -3897,20 +3841,20 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung Suchen: - - + + Match case Groß-/Kleinschreibung beachten - - + + Regular expression Regulärer Ausdruck - - + + Highlight all matches Alle Treffer hervorheben @@ -4252,25 +4196,25 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung SessionsWindow - + Telnet Error Telnet-Fehler - + Telnet error: %1. Telnet-Fehler: %1. - - + + Serial Error Serieller Fehler - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung %1. - + Raw Socket Error Raw-Socket-Fehler - + Raw Socket error: %1. Raw-Socket-Fehler: %1. - + Name Pipe Error Name-Pipe-Fehler - + Name Pipe error: %1. Name-Pipe-Fehler: %1. - - + + SSH2 Error SSH2-Fehler - - + + SSH2 error: %1. SSH2-Fehler: %1. - - + + Open URL URL öffnen - - + + Cannot open URL %1. URL %1 kann nicht geöffnet werden. - + Select Files to Send using Zmodem Wählen Sie Dateien aus, die mit Zmodem gesendet werden sollen - + All Files (*) Alle Dateien (*) - + Start Local Shell Lokale Shell starten - + Cannot start local shell: %1. Lokale Shell kann nicht gestartet werden: %1. - + Serial port %1 has been removed. Serieller Port %1 wurde entfernt. - + Save log... Log speichern... - + log files (*.log) Log-Dateien (*.log) - + Save log Log speichern - - - + + + Cannot write file %1: %2. Datei %1 kann nicht geschrieben werden: %2. - + Save Raw log... Raw-Log speichern... - + binary files (*.bin) Binärdateien (*.bin) - + Save Raw log Raw-Log speichern - + Unlock Session Sitzung entsperren - + Wrong password! Falsches Passwort! - + Receive ASCII File ASCII-Datei empfangen @@ -4662,6 +4606,34 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung Übertragungs-Informationen + + TerminalDisplay + + + Size: XXX x XXX + Größe: XXX x XXX + + + + Size: %1 x %2 + Größe: %1 x %2 + + + + Paste multiline text + Mehrzeiligen Text einfügen + + + + Are you sure you want to paste this text? + Möchten Sie diesen Text wirklich einfügen? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Die Ausgabe wurde durch Drücken von Strg+S <a href="http://en.wikipedia.org/wiki/Flow_control">angehalten</a>. Drücken Sie <b>Strg+Q</b>, um fortzufahren.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ Wenn Sie eine andere Shell verwenden müssen, erstellen Sie bitte eine Sitzung %1 Zeichen überschreiben + + UrlFilter + + + Follow link (ctrl + click) + Link folgen (Strg + Klick) + + + + Follow path (ctrl + click) + Pfad folgen (Strg + Klick) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Kein Tastaturübersetzer verfügbar. Die Informationen, die zum Konvertieren von Tastendrücken in Zeichen, die an das Terminal gesendet werden sollen, fehlen. + + keyMapManager diff --git a/lang/quardCRT_en_US.ts b/lang/quardCRT_en_US.ts index bf8f154c..a02cc2ec 100644 --- a/lang/quardCRT_en_US.ts +++ b/lang/quardCRT_en_US.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning @@ -285,7 +285,7 @@ - + Ready @@ -464,7 +464,7 @@ - + Help @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect - + Disconnect All - + Disconnect all sessions - + Clone Session - + Clone current session <Ctrl+Shift+T> @@ -595,564 +596,564 @@ - + Log Session - + Create a log file for current session - + Raw Log Session - + Create a raw log file for current session - + Hex View - + Show/Hide Hex View for current session - + Exit - + Quit the application - + Copy - + Copy the selected text to the clipboard <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> - + Paste - + Paste the clipboard text to the current session <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> - + Copy and Paste - + Copy the selected text to the clipboard and paste to the current session - + Select All - + Select all text in the current session <Ctrl+Shift+A> - + Find... - + Find text in the current session <Ctrl+F> - + Print Screen - + Print current screen - + Screen Shot - + Screen shot current screen <Alt+P> - + Session Export - + Export current session to a file <Alt+O> - + Clear Scrollback - + Clear the contents of the scrollback rows - + Clear Screen - + Clear the contents of the current screen - + Clear Screen and Scrollback - + Clear the contents of the screen and scrollback - + Reset - + Reset terminal emulator - + Zoom In - + Zoom In <Ctrl+"="> - + Zoom Out - + Zoom Out <Ctrl+"-"> - - + + Zoom Reset - + Layout - + Single Layout - + Single layout - + Two Columns Layout - + Two columns layout - + Three Columns Layout - + Three columns layout - + Two Rows Layout - + Two rows layout - + Three Rows Layout - + Three rows layout - + Grid Layout - + Grid layout - + Two Rows Right Layout - + Two rows right layout - + Two Columns Bottom Layout - + Two columns bottom layout - + Flip Layout - + Flip layout - + Menu Bar - + Show/Hide Menu Bar <Alt+U> - + Show/Hide Tool Bar - + Status Bar - + Show/Hide Status Bar - + Command Window - + Show/Hide Command Window - + Connect Bar - + Show/Hide Connect Bar - + Side Window - + Show/Hide Side Window - + Windows Transparency - + Enable/Disable alpha transparency - + Vertical Scroll Bar - + Show/Hide Vertical Scroll Bar - + Allways On Top - + Show window always on top - + Full Screen - + Toggle between full screen and normal mode <Alt+Enter> - + Session Options... - + Configure session options - + Global Options... - + Configure global options - + Real-time Save Options - + Real-time save session options and global options - + Save Settings Now - + Save options configuration now - + Send ASCII... - + Send ASCII file - + Receive ASCII... - + Receive ASCII file - + Send Binary... - + Send Binary file - + Send Kermit... - + Send a file using Kermit - + Receive Kermit... - + Receive a file using Kermit - + Send Xmodem... - + Send a file using Xmodem - + Receive Xmodem... - + Receive a file using Xmodem - + Send Ymodem... - + Send a file using Ymodem - + Receive Ymodem... - + Receive a file using Ymodem - + Zmodem Upload List... - + Display Zmodem file upload list - + Start Zmodem Upload - + Start Zmodem file upload - + Start TFTP Server - + Start/Stop the TFTP server - + Run... - + Run a script - + Cancel @@ -1213,759 +1214,759 @@ - + Cancel script execution - + Start Recording Script - + Start recording script - + Stop Recording Script... - + Stop recording script - + Cancel Recording Script - + Cancel recording script - + Add Bookmark - + Add a bookmark - - + + Remove Bookmark - + Remove a bookmark - - + + Clean All Bookmark - + Clean all bookmark - + Keymap Manager - + Display keymap editor - + Create Public Key... - + Create a public key - + Publickey Manager - + Display publickey manager - + Internal Command - + Display Internal Command window - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color - + Set theme color, cancel to use default - - + + Keyborad Shortcuts Reference - + Display keyborad shortcuts reference - - + + Privacy Statement - + Display privacy statement - - + + About Python - + Display about Python dialog - + Laboratory - - + + SSH Scanning - + Display SSH scanning dialog - + Plugin metaData not found! - + Plugin api version not found! - + Plugin api version not match! - + Plugin menu not found! - + Plugin init failed! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! - + Select Files to Send as ASCII - - + + Text Files (*.txt);;All Files (*) - + Save Received Data as ASCII - + Select Files to Send as BINARY - - - - - - + + + + + + All Files (*) - + Select Files to Send using Kermit - + Select Files to Send using Xmodem - + Save Received Files using Xmodem - + Select Files to Send using Ymodem - + Select Files to Send using Zmodem - + Select a script file - + Python Files (*.py);;All Files (*) - + Select color - + Are you sure to disconnect " - + " session? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. - + This software does not collect any personal information, and does not send any information to the server. - + This software does not contain any malicious code, and does not contain any backdoors. - + This software is open source software, you can view the source code on the github website. - + This software is provided as is, without any warranty. - + If you have any questions or suggestions, please contact the author. - + Version - + Commit - + Date - - + + Author - + Website - + Tab - + Arrange sessions in tabs - + Tile - + Arrange sessions in non-overlapping tiles - + Cascade - + Arrange sessions to overlap each other - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light - + Switch to light theme - + Dark - + Switch to dark theme - + Display help - + Check Update - + Check for updates - - + + About - + Display about dialog - + About Qt - + Display about Qt dialog - + Plugin Info - + Display plugin information dialog - + PrintScreen saved to %1 - + Save Screenshot - + Image Files (*.jpg) - - + + Screenshot saved to %1 - + Save Session Export - + Text Files (*.txt);;HTML Files (*.html) - + Text Files (*.txt) - + HTML Files (*.html) - + Session Export saved to %1 - + Session Export failed to save to %1 - + Select a directory - + Select a bookmark - + Are you sure to clean all bookmark? - + Port - + Video background is enabled, please enable animation in global options (more system resources) or change background image. - + Session information get failed. - + Telnet - - + Telnet - + Serial - - + Serial - + Raw - - + Raw - + NamePipe - - + NamePipe - - + + Local Shell - + Local Shell - - + Global Shortcuts: - + show/hide menu bar - + connect to LocalShell - + clone current session - + switch ui to STD mode - + switch ui to MINI mode - + switch to previous session - + switch to next session - + switch to session [num] - + Go to line start - + Go to line end - + There are sessions that have not yet been unlocked, please unlock them first. - + Are you sure to quit? @@ -2696,8 +2697,8 @@ - - + + Warning @@ -2731,7 +2732,7 @@ If you need to use another shell, please create a session through [quick-connect - + The Default Local Shell is not a valid file! @@ -2781,7 +2782,7 @@ If you need to use another shell, please create a session through [quick-connect - + The User Plugins Path is not a directory! @@ -2865,93 +2866,36 @@ If you need to use another shell, please create a session through [quick-connect - + Copy - + Paste - + Select All - + Find - + Zoom In - + Zoom Out - - Session - - - Bell in session '%1' - - - - - TerminalDisplay - - - Size: XXX x XXX - - - - - Size: %1 x %2 - - - - - Paste multiline text - - - - - Are you sure you want to paste this text? - - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - - - - - UrlFilter - - - Follow link (ctrl + click) - - - - - Follow path (ctrl + click) - - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - - - LockSessionWindow @@ -3480,47 +3424,47 @@ If you need to use another shell, please create a session through [quick-connect QObject - + Un-named Color Scheme - + Accessible Color Scheme - + Open Link - + Copy Link Address - + Send Email To... - + Copy Email Address - + Open Path - + Open Containing Folder - + Copy Path @@ -3583,12 +3527,12 @@ If you need to use another shell, please create a session through [quick-connect QTermWidget - + Color Scheme Error - + Cannot load color scheme: %1 @@ -3890,20 +3834,20 @@ If you need to use another shell, please create a session through [quick-connect - - + + Match case - - + + Regular expression - - + + Highlight all matches @@ -4242,152 +4186,152 @@ If you need to use another shell, please create a session through [quick-connect SessionsWindow - + Telnet Error - + Telnet error: %1. - - + + Serial Error - + Serial error: %0 %1. - + Raw Socket Error - + Raw Socket error: %1. - + Name Pipe Error - + Name Pipe error: %1. - - + + SSH2 Error - - + + SSH2 error: %1. - - + + Open URL - - + + Cannot open URL %1. - + Select Files to Send using Zmodem - + All Files (*) - + Start Local Shell - + Cannot start local shell: %1. - + Serial port %1 has been removed. - + Save log... - + log files (*.log) - + Save log - - - + + + Cannot write file %1: %2. - + Save Raw log... - + binary files (*.bin) - + Save Raw log - + Unlock Session - + Wrong password! - + Receive ASCII File @@ -4644,6 +4588,34 @@ If you need to use another shell, please create a session through [quick-connect + + TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + UndoStack @@ -4662,6 +4634,27 @@ If you need to use another shell, please create a session through [quick-connect + + UrlFilter + + + Follow link (ctrl + click) + + + + + Follow path (ctrl + click) + + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + keyMapManager diff --git a/lang/quardCRT_es_ES.ts b/lang/quardCRT_es_ES.ts index ac1437a6..9207e0df 100644 --- a/lang/quardCRT_es_ES.ts +++ b/lang/quardCRT_es_ES.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Barra de herramientas @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Advertencia @@ -285,7 +285,7 @@ - + Ready Preparado @@ -464,7 +464,7 @@ - + Help Ayuda @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Introduzca el host <Alt+R> para conectar - + Disconnect All Desconectar todo - + Disconnect all sessions Desconectar todas las sesiones - + Clone Session Clonar sesión - + Clone current session <Ctrl+Shift+T> Clonar sesión actual <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Bloquear sesión - + Log Session Registro de sesión - + Create a log file for current session Crear un archivo de registro para la sesión actual - + Raw Log Session Registro de sesión en bruto - + Create a raw log file for current session Crear un archivo de registro en bruto para la sesión actual - + Hex View Vista hexadecimal - + Show/Hide Hex View for current session Mostrar/Ocultar vista hexadecimal para la sesión actual - + Exit Salir - + Quit the application Salir de la aplicación - + Copy Copiar - + Copy the selected text to the clipboard <Command+C> Copiar el texto seleccionado al portapapeles <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Copiar el texto seleccionado al portapapeles <Ctrl+Ins> - + Paste Pegar - + Paste the clipboard text to the current session <Command+V> Pegar el texto del portapapeles a la sesión actual <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Pegar el texto del portapapeles a la sesión actual <Shift+Ins> - + Copy and Paste Copiar y pegar - + Copy the selected text to the clipboard and paste to the current session Copiar el texto seleccionado al portapapeles y pegar a la sesión actual - + Select All Seleccionar todo - + Select all text in the current session <Ctrl+Shift+A> Seleccionar todo el texto en la sesión actual <Ctrl+Shift+A> - + Find... Buscar... - + Find text in the current session <Ctrl+F> Buscar texto en la sesión actual <Ctrl+F> - + Print Screen Imprimir pantalla - + Print current screen Imprimir pantalla actual - + Screen Shot Captura de pantalla - + Screen shot current screen <Alt+P> Captura de pantalla de la pantalla actual <Alt+P> - + Session Export Exportar sesión - + Export current session to a file <Alt+O> Exportar sesión actual a un archivo <Alt+O> - + Clear Scrollback Borrar desplazamiento - + Clear the contents of the scrollback rows Borrar el contenido de las filas de desplazamiento - + Clear Screen Borrar pantalla - + Clear the contents of the current screen Borrar el contenido de la pantalla actual - + Clear Screen and Scrollback Borrar pantalla y desplazamiento - + Clear the contents of the screen and scrollback Borrar el contenido de la pantalla y el desplazamiento - + Reset Reiniciar - + Reset terminal emulator Reiniciar emulador de terminal - + Zoom In Acercar - + Zoom In <Ctrl+"="> Acercar <Ctrl+"="> - + Zoom Out Alejar - + Zoom Out <Ctrl+"-"> Alejar <Ctrl+"-"> - - + + Zoom Reset Restablecer zoom - + Layout Diseño - + Single Layout Diseño único - + Single layout Diseño único - + Two Columns Layout Diseño de dos columnas - + Two columns layout Diseño de dos columnas - + Three Columns Layout Diseño de tres columnas - + Three columns layout Diseño de tres columnas - + Two Rows Layout Diseño de dos filas - + Two rows layout Diseño de dos filas - + Three Rows Layout Diseño de tres filas - + Three rows layout Diseño de tres filas - + Grid Layout Diseño de cuadrícula - + Grid layout Diseño de cuadrícula - + Two Rows Right Layout Diseño de dos filas a la derecha - + Two rows right layout Diseño de dos filas a la derecha - + Two Columns Bottom Layout Diseño de dos columnas en la parte inferior - + Two columns bottom layout Diseño de dos columnas en la parte inferior - + Flip Layout Voltear diseño - + Flip layout Voltear diseño - + Menu Bar Barra de menús - + Show/Hide Menu Bar <Alt+U> Mostrar/Ocultar barra de menús <Alt+U> - + Show/Hide Tool Bar Mostrar/Ocultar barra de herramientas - + Status Bar Barra de estado - + Show/Hide Status Bar Mostrar/Ocultar barra de estado - + Command Window Ventana de comandos - + Show/Hide Command Window Mostrar/Ocultar ventana de comandos - + Connect Bar Barra de conexión - + Show/Hide Connect Bar Mostrar/Ocultar barra de conexión - + Side Window Ventana lateral - + Show/Hide Side Window Mostrar/Ocultar ventana lateral - + Windows Transparency Transparencia de ventanas - + Enable/Disable alpha transparency Habilitar/Deshabilitar transparencia alfa - + Vertical Scroll Bar Barra de desplazamiento vertical - + Show/Hide Vertical Scroll Bar Mostrar/Ocultar barra de desplazamiento vertical - + Allways On Top Siempre encima - + Show window always on top Mostrar ventana siempre encima - + Full Screen Pantalla completa - + Toggle between full screen and normal mode <Alt+Enter> Alternar entre pantalla completa y modo normal <Alt+Enter> - + Session Options... Opciones de sesión... - + Configure session options Configurar opciones de sesión - + Global Options... Opciones globales... - + Configure global options Configurar opciones globales - + Real-time Save Options Opciones de guardado en tiempo real - + Real-time save session options and global options Opciones de guardado en tiempo real de la sesión y opciones globales - + Save Settings Now Guardar configuración ahora - + Save options configuration now Guardar configuración de opciones ahora - + Send ASCII... Enviar ASCII... - + Send ASCII file Enviar archivo ASCII - + Receive ASCII... Recibir ASCII... - + Receive ASCII file Recibir archivo ASCII - + Send Binary... Enviar binario... - + Send Binary file Enviar archivo binario - + Send Kermit... Enviar Kermit... - + Send a file using Kermit Enviar un archivo usando Kermit - + Receive Kermit... Recibir Kermit... - + Receive a file using Kermit Recibir un archivo usando Kermit - + Send Xmodem... Enviar Xmodem... - + Send a file using Xmodem Enviar un archivo usando Xmodem - + Receive Xmodem... Recibir Xmodem... - + Receive a file using Xmodem Recibir un archivo usando Xmodem - + Send Ymodem... Enviar Ymodem... - + Send a file using Ymodem Enviar un archivo usando Ymodem - + Receive Ymodem... Recibir Ymodem... - + Receive a file using Ymodem Recibir un archivo usando Ymodem - + Zmodem Upload List... Lista de subida Zmodem... - + Display Zmodem file upload list Mostrar lista de subida de archivos Zmodem - + Start Zmodem Upload Iniciar subida Zmodem - + Start Zmodem file upload Iniciar subida de archivo Zmodem - + Start TFTP Server Iniciar servidor TFTP - + Start/Stop the TFTP server Iniciar/Detener el servidor TFTP - + Run... Ejecutar... - + Run a script Ejecutar un script - + Cancel Cancelar @@ -1213,759 +1214,759 @@ Cambiar color - + Cancel script execution Cancelar ejecución de script - + Start Recording Script Iniciar grabación de script - + Start recording script Iniciar grabación de script - + Stop Recording Script... Detener grabación de script... - + Stop recording script Detener grabación de script - + Cancel Recording Script Cancelar grabación de script - + Cancel recording script Cancelar grabación de script - + Add Bookmark Añadir marcador - + Add a bookmark Añadir un marcador - - + + Remove Bookmark Eliminar marcador - + Remove a bookmark Eliminar un marcador - - + + Clean All Bookmark Limpiar todos los marcadores - + Clean all bookmark Limpiar todos los marcadores - + Keymap Manager Administrador de mapas de teclas - + Display keymap editor Mostrar editor de mapas de teclas - + Create Public Key... Crear clave pública... - + Create a public key Crear una clave pública - + Publickey Manager Administrador de claves públicas - + Display publickey manager Mostrar administrador de claves públicas - + Internal Command Comando interno - + Display Internal Command window Mostrar ventana de comando interno - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color Color del tema - + Set theme color, cancel to use default Establecer color del tema, cancelar para usar el predeterminado - - + + Keyborad Shortcuts Reference Referencia de atajos de teclado - + Display keyborad shortcuts reference Mostrar referencia de atajos de teclado - - + + Privacy Statement Declaración de privacidad - + Display privacy statement Mostrar declaración de privacidad - - + + About Python Acerca de Python - + Display about Python dialog Mostrar diálogo acerca de Python - + Laboratory Laboratorio - - + + SSH Scanning Escaneo SSH - + Display SSH scanning dialog Mostrar diálogo de escaneo SSH - + Plugin metaData not found! ¡No se encontraron metadatos del complemento! - + Plugin api version not found! ¡No se encontró la versión de la API del complemento! - + Plugin api version not match! ¡La versión de la API del complemento no coincide! - + Plugin menu not found! ¡Menú del complemento no encontrado! - + Plugin init failed! ¡Error al inicializar el complemento! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! ¡La sesión de difusión no puede transferir archivos! - + Select Files to Send as ASCII Seleccionar archivos para enviar como ASCII - - + + Text Files (*.txt);;All Files (*) Archivos de texto (*.txt);;Todos los archivos (*) - + Save Received Data as ASCII Guardar datos recibidos como ASCII - + Select Files to Send as BINARY Seleccionar archivos para enviar como BINARIO - - - - - - + + + + + + All Files (*) Todos los archivos (*) - + Select Files to Send using Kermit Seleccionar archivos para enviar usando Kermit - + Select Files to Send using Xmodem Seleccionar archivos para enviar usando Xmodem - + Save Received Files using Xmodem Guardar archivos recibidos usando Xmodem - + Select Files to Send using Ymodem Seleccionar archivos para enviar usando Ymodem - + Select Files to Send using Zmodem Seleccionar archivos para enviar usando Zmodem - + Select a script file Seleccionar un archivo de script - + Python Files (*.py);;All Files (*) Archivos de Python (*.py);;Todos los archivos (*) - + Select color Seleccionar color - + Are you sure to disconnect " ¿Está seguro de desconectar " - + " session? " sesión? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Este software es un emulador de terminal que proporciona una conexión de shell seguro (SSH), una conexión telnet, una conexión de puerto serie y otras funciones. - + This software does not collect any personal information, and does not send any information to the server. Este software no recopila ninguna información personal y no envía ninguna información al servidor. - + This software does not contain any malicious code, and does not contain any backdoors. Este software no contiene ningún código malicioso y no contiene ninguna puerta trasera. - + This software is open source software, you can view the source code on the github website. Este software es un software de código abierto, puede ver el código fuente en el sitio web de github. - + This software is provided as is, without any warranty. Este software se proporciona tal cual, sin garantía alguna. - + If you have any questions or suggestions, please contact the author. Si tiene alguna pregunta o sugerencia, póngase en contacto con el autor. - + Version Versión - + Commit Confirmar - + Date Fecha - - + + Author Autor - + Website Sitio web - + Tab Pestaña - + Arrange sessions in tabs Organizar sesiones en pestañas - + Tile Mosaico - + Arrange sessions in non-overlapping tiles Organizar sesiones en mosaicos no superpuestos - + Cascade Cascada - + Arrange sessions to overlap each other Organizar sesiones para que se superpongan entre sí - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light Claro - + Switch to light theme Cambiar a tema claro - + Dark Oscuro - + Switch to dark theme Cambiar a tema oscuro - + Display help Mostrar ayuda - + Check Update Comprobar actualizaciones - + Check for updates Buscar actualizaciones - - + + About Acerca de - + Display about dialog Mostrar diálogo acerca de - + About Qt Acerca de Qt - + Display about Qt dialog Mostrar diálogo acerca de Qt - + Plugin Info Información del complemento - + Display plugin information dialog Mostrar diálogo de información del complemento - + PrintScreen saved to %1 Imprimir pantalla guardada en %1 - + Save Screenshot Guardar captura de pantalla - + Image Files (*.jpg) Archivos de imagen (*.jpg) - - + + Screenshot saved to %1 Captura de pantalla guardada en %1 - + Save Session Export Guardar exportación de sesión - + Text Files (*.txt);;HTML Files (*.html) Archivos de texto (*.txt);;Archivos HTML (*.html) - + Text Files (*.txt) Archivos de texto (*.txt) - + HTML Files (*.html) Archivos HTML (*.html) - + Session Export saved to %1 Exportación de sesión guardada en %1 - + Session Export failed to save to %1 Error al guardar la exportación de sesión en %1 - + Select a directory Seleccionar un directorio - + Select a bookmark Seleccionar un marcador - + Are you sure to clean all bookmark? ¿Está seguro de limpiar todos los marcadores? - + Port Puerto - + Video background is enabled, please enable animation in global options (more system resources) or change background image. El fondo de video está habilitado, habilite la animación en las opciones globales (más recursos del sistema) o cambie la imagen de fondo. - + Session information get failed. Error al obtener la información de la sesión. - + Telnet - - + Telnet - + Serial - Serie - - + Serial Serie - + Raw - Crudo - - + Raw Crudo - + NamePipe - Nombre de tubería - - + NamePipe Nombre de tubería - - + + Local Shell Shell local - + Local Shell - Shell local - - + Global Shortcuts: Atajos globales: - + show/hide menu bar mostrar/ocultar barra de menús - + connect to LocalShell conectar a Shell local - + clone current session clonar sesión actual - + switch ui to STD mode cambiar la interfaz de usuario al modo STD - + switch ui to MINI mode cambiar la interfaz de usuario al modo MINI - + switch to previous session cambiar a la sesión anterior - + switch to next session cambiar a la siguiente sesión - + switch to session [num] cambiar a la sesión [num] - + Go to line start Ir al inicio de la línea - + Go to line end Ir al final de la línea - + There are sessions that have not yet been unlocked, please unlock them first. Hay sesiones que aún no se han desbloqueado, desbloquéelas primero. - + Are you sure to quit? ¿Está seguro de salir? @@ -2707,8 +2708,8 @@ - - + + Warning Advertencia @@ -2745,7 +2746,7 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g - + The Default Local Shell is not a valid file! ¡El Shell local predeterminado no es un archivo válido! @@ -2795,7 +2796,7 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g Transferir - + The User Plugins Path is not a directory! ¡La ruta de los complementos de usuario no es un directorio! @@ -2869,93 +2870,36 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g Comando interno - + Copy Copiar - + Paste Pegar - + Select All Seleccionar todo - + Find Buscar - + Zoom In Acercar - + Zoom Out Alejar - - Session - - - Bell in session '%1' - Campana en la sesión '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Tamaño: XXX x XXX - - - - Size: %1 x %2 - Tamaño: %1 x %2 - - - - Paste multiline text - Pegar texto de varias líneas - - - - Are you sure you want to paste this text? - ¿Está seguro de que desea pegar este texto? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>La salida ha sido <a href="http://en.wikipedia.org/wiki/Flow_control">suspendida</a> al presionar Ctrl+S. Presione <b>Ctrl+Q</b> para reanudar.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Seguir enlace (ctrl + clic) - - - - Follow path (ctrl + click) - Seguir ruta (ctrl + clic) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - No hay traductor de teclado disponible. Falta la información necesaria para convertir las pulsaciones de teclas en caracteres para enviar al terminal. - - LockSessionWindow @@ -3484,47 +3428,47 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g QObject - + Un-named Color Scheme Esquema de color sin nombre - + Accessible Color Scheme Esquema de color accesible - + Open Link Abrir enlace - + Copy Link Address Copiar dirección del enlace - + Send Email To... Enviar correo electrónico a... - + Copy Email Address Copiar dirección de correo electrónico - + Open Path Abrir ruta - + Open Containing Folder Abrir carpeta contenedora - + Copy Path Copiar ruta @@ -3587,12 +3531,12 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g QTermWidget - + Color Scheme Error Error de esquema de color - + Cannot load color scheme: %1 No se puede cargar el esquema de color: %1 @@ -3897,20 +3841,20 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g Buscar: - - + + Match case Coincidir mayúsculas y minúsculas - - + + Regular expression Expresión regular - - + + Highlight all matches Resaltar todas las coincidencias @@ -4252,25 +4196,25 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g SessionsWindow - + Telnet Error Error de Telnet - + Telnet error: %1. Error de Telnet: %1. - - + + Serial Error Error de serie - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g %1. - + Raw Socket Error Error de socket sin formato - + Raw Socket error: %1. Error de socket sin formato: %1. - + Name Pipe Error Error de nombre de tubería - + Name Pipe error: %1. Error de nombre de tubería: %1. - - + + SSH2 Error Error de SSH2 - - + + SSH2 error: %1. Error de SSH2: %1. - - + + Open URL Abrir URL - - + + Cannot open URL %1. No se puede abrir la URL %1. - + Select Files to Send using Zmodem Seleccionar archivos para enviar usando Zmodem - + All Files (*) Todos los archivos (*) - + Start Local Shell Iniciar shell local - + Cannot start local shell: %1. No se puede iniciar el shell local: %1. - + Serial port %1 has been removed. El puerto serie %1 ha sido eliminado. - + Save log... Guardar registro... - + log files (*.log) archivos de registro (*.log) - + Save log Guardar registro - - - + + + Cannot write file %1: %2. No se puede escribir el archivo %1: %2. - + Save Raw log... Guardar registro sin formato... - + binary files (*.bin) archivos binarios (*.bin) - + Save Raw log Guardar registro sin formato - + Unlock Session Desbloquear sesión - + Wrong password! ¡Contraseña incorrecta! - + Receive ASCII File Recibir archivo ASCII @@ -4662,6 +4606,34 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g Información de transferencia + + TerminalDisplay + + + Size: XXX x XXX + Tamaño: XXX x XXX + + + + Size: %1 x %2 + Tamaño: %1 x %2 + + + + Paste multiline text + Pegar texto de varias líneas + + + + Are you sure you want to paste this text? + ¿Está seguro de que desea pegar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>La salida ha sido <a href="http://en.wikipedia.org/wiki/Flow_control">suspendida</a> al presionar Ctrl+S. Presione <b>Ctrl+Q</b> para reanudar.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ Si necesita usar otro shell, cree una sesión a través de [conexión rápida &g Sobrescribir %1 caracteres + + UrlFilter + + + Follow link (ctrl + click) + Seguir enlace (ctrl + clic) + + + + Follow path (ctrl + click) + Seguir ruta (ctrl + clic) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + No hay traductor de teclado disponible. Falta la información necesaria para convertir las pulsaciones de teclas en caracteres para enviar al terminal. + + keyMapManager diff --git a/lang/quardCRT_fr_FR.ts b/lang/quardCRT_fr_FR.ts index cf39fc90..e914a73d 100644 --- a/lang/quardCRT_fr_FR.ts +++ b/lang/quardCRT_fr_FR.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Barre d'outils @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Attention @@ -285,7 +285,7 @@ - + Ready Prêt @@ -464,7 +464,7 @@ - + Help Aide @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Entrer l'hôte <Alt+R> pour se connecter - + Disconnect All Déconnecter tout - + Disconnect all sessions Déconnecter toutes les sessions - + Clone Session Cloner la session - + Clone current session <Ctrl+Shift+T> Cloner la session en cours <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Verrouiller la session - + Log Session Journaliser la session - + Create a log file for current session Créer un fichier journal pour la session en cours - + Raw Log Session Journal brut de la session - + Create a raw log file for current session Créer un fichier journal brut pour la session en cours - + Hex View Vue hexadécimale - + Show/Hide Hex View for current session Afficher/Masquer la vue hexadécimale pour la session en cours - + Exit Quitter - + Quit the application Quitter l'application - + Copy Copier - + Copy the selected text to the clipboard <Command+C> Copier le texte sélectionné dans le presse-papiers <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Copier le texte sélectionné dans le presse-papiers <Ctrl+Ins> - + Paste Coller - + Paste the clipboard text to the current session <Command+V> Coller le texte du presse-papiers dans la session en cours <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Coller le texte du presse-papiers dans la session en cours <Shift+Ins> - + Copy and Paste Copier et coller - + Copy the selected text to the clipboard and paste to the current session Copier le texte sélectionné dans le presse-papiers et coller dans la session en cours - + Select All Tout sélectionner - + Select all text in the current session <Ctrl+Shift+A> Sélectionner tout le texte dans la session en cours <Ctrl+Shift+A> - + Find... Rechercher... - + Find text in the current session <Ctrl+F> Rechercher du texte dans la session en cours <Ctrl+F> - + Print Screen Imprimer l'écran - + Print current screen Imprimer l'écran en cours - + Screen Shot Capture d'écran - + Screen shot current screen <Alt+P> Capture d'écran de l'écran en cours <Alt+P> - + Session Export Exportation de la session - + Export current session to a file <Alt+O> Exporter la session en cours vers un fichier <Alt+O> - + Clear Scrollback Effacer le défilement - + Clear the contents of the scrollback rows Effacer le contenu des lignes de défilement - + Clear Screen Effacer l'écran - + Clear the contents of the current screen Effacer le contenu de l'écran en cours - + Clear Screen and Scrollback Effacer l'écran et le défilement - + Clear the contents of the screen and scrollback Effacer le contenu de l'écran et du défilement - + Reset Réinitialiser - + Reset terminal emulator Réinitialiser l'émulateur de terminal - + Zoom In Agrandir - + Zoom In <Ctrl+"="> Agrandir <Ctrl+"="> - + Zoom Out Réduire - + Zoom Out <Ctrl+"-"> Réduire <Ctrl+"-"> - - + + Zoom Reset Réinitialiser le zoom - + Layout Disposition - + Single Layout Disposition simple - + Single layout Disposition simple - + Two Columns Layout Disposition à deux colonnes - + Two columns layout Disposition à deux colonnes - + Three Columns Layout Disposition à trois colonnes - + Three columns layout Disposition à trois colonnes - + Two Rows Layout Disposition à deux rangées - + Two rows layout Disposition à deux rangées - + Three Rows Layout Disposition à trois rangées - + Three rows layout Disposition à trois rangées - + Grid Layout Disposition en grille - + Grid layout Disposition en grille - + Two Rows Right Layout Disposition à deux rangées à droite - + Two rows right layout Disposition à deux rangées à droite - + Two Columns Bottom Layout Disposition à deux colonnes en bas - + Two columns bottom layout Disposition à deux colonnes en bas - + Flip Layout Retourner la disposition - + Flip layout Retourner la disposition - + Menu Bar Barre de menu - + Show/Hide Menu Bar <Alt+U> Afficher/Masquer la barre de menu <Alt+U> - + Show/Hide Tool Bar Afficher/Masquer la barre d'outils - + Status Bar Barre d'état - + Show/Hide Status Bar Afficher/Masquer la barre d'état - + Command Window Fenêtre de commande - + Show/Hide Command Window Afficher/Masquer la fenêtre de commande - + Connect Bar Barre de connexion - + Show/Hide Connect Bar Afficher/Masquer la barre de connexion - + Side Window Fenêtre latérale - + Show/Hide Side Window Afficher/Masquer la fenêtre latérale - + Windows Transparency Transparence des fenêtres - + Enable/Disable alpha transparency Activer/Désactiver la transparence alpha - + Vertical Scroll Bar Barre de défilement verticale - + Show/Hide Vertical Scroll Bar Afficher/Masquer la barre de défilement verticale - + Allways On Top Toujours au premier plan - + Show window always on top Afficher la fenêtre toujours au premier plan - + Full Screen Plein écran - + Toggle between full screen and normal mode <Alt+Enter> Basculer entre le mode plein écran et le mode normal <Alt+Entrée> - + Session Options... Options de la session... - + Configure session options Configurer les options de la session - + Global Options... Options globales... - + Configure global options Configurer les options globales - + Real-time Save Options Options d'enregistrement en temps réel - + Real-time save session options and global options Enregistrer en temps réel les options de session et les options globales - + Save Settings Now Enregistrer les paramètres maintenant - + Save options configuration now Enregistrer la configuration des options maintenant - + Send ASCII... Envoyer ASCII... - + Send ASCII file Envoyer un fichier ASCII - + Receive ASCII... Recevoir ASCII... - + Receive ASCII file Recevoir un fichier ASCII - + Send Binary... Envoyer binaire... - + Send Binary file Envoyer un fichier binaire - + Send Kermit... Envoyer Kermit... - + Send a file using Kermit Envoyer un fichier en utilisant Kermit - + Receive Kermit... Recevoir Kermit... - + Receive a file using Kermit Recevoir un fichier en utilisant Kermit - + Send Xmodem... Envoyer Xmodem... - + Send a file using Xmodem Envoyer un fichier en utilisant Xmodem - + Receive Xmodem... Recevoir Xmodem... - + Receive a file using Xmodem Recevoir un fichier en utilisant Xmodem - + Send Ymodem... Envoyer Ymodem... - + Send a file using Ymodem Envoyer un fichier en utilisant Ymodem - + Receive Ymodem... Recevoir Ymodem... - + Receive a file using Ymodem Recevoir un fichier en utilisant Ymodem - + Zmodem Upload List... Liste de téléchargement Zmodem... - + Display Zmodem file upload list Afficher la liste de téléchargement de fichiers Zmodem - + Start Zmodem Upload Démarrer le téléchargement Zmodem - + Start Zmodem file upload Démarrer le téléchargement de fichiers Zmodem - + Start TFTP Server Démarrer le serveur TFTP - + Start/Stop the TFTP server Démarrer/Arrêter le serveur TFTP - + Run... Exécuter... - + Run a script Exécuter un script - + Cancel Annuler @@ -1213,759 +1214,759 @@ Changer la couleur - + Cancel script execution Annuler l'exécution du script - + Start Recording Script Commencer l'enregistrement du script - + Start recording script Commencer l'enregistrement du script - + Stop Recording Script... Arrêter l'enregistrement du script... - + Stop recording script Arrêter l'enregistrement du script - + Cancel Recording Script Annuler l'enregistrement du script - + Cancel recording script Annuler l'enregistrement du script - + Add Bookmark Ajouter un marque-page - + Add a bookmark Ajouter un marque-page - - + + Remove Bookmark Supprimer un marque-page - + Remove a bookmark Supprimer un marque-page - - + + Clean All Bookmark Nettoyer tous les marque-pages - + Clean all bookmark Nettoyer tous les marque-pages - + Keymap Manager Gestionnaire de mappage des touches - + Display keymap editor Afficher l'éditeur de mappage des touches - + Create Public Key... Créer une clé publique... - + Create a public key Créer une clé publique - + Publickey Manager Gestionnaire de clés publiques - + Display publickey manager Afficher le gestionnaire de clés publiques - + Internal Command Commande interne - + Display Internal Command window Afficher la fenêtre de commande interne - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color Couleur du thème - + Set theme color, cancel to use default Définir la couleur du thème, annuler pour utiliser la valeur par défaut - - + + Keyborad Shortcuts Reference Référence des raccourcis clavier - + Display keyborad shortcuts reference Afficher la référence des raccourcis clavier - - + + Privacy Statement Déclaration de confidentialité - + Display privacy statement Afficher la déclaration de confidentialité - - + + About Python À propos de Python - + Display about Python dialog Afficher la boîte de dialogue À propos de Python - + Laboratory Laboratoire - - + + SSH Scanning Exploration SSH - + Display SSH scanning dialog Afficher la boîte de dialogue d'exploration SSH - + Plugin metaData not found! Métadonnées du plugin introuvables ! - + Plugin api version not found! Version de l'API du plugin introuvable ! - + Plugin api version not match! La version de l'API du plugin ne correspond pas ! - + Plugin menu not found! Menu du plugin introuvable ! - + Plugin init failed! Échec de l'initialisation du plugin ! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! La session de diffusion ne peut pas transférer de fichier ! - + Select Files to Send as ASCII Sélectionner les fichiers à envoyer en ASCII - - + + Text Files (*.txt);;All Files (*) Fichiers texte (*.txt);;Tous les fichiers (*) - + Save Received Data as ASCII Enregistrer les données reçues en ASCII - + Select Files to Send as BINARY Sélectionner les fichiers à envoyer en BINAIRE - - - - - - + + + + + + All Files (*) Tous les fichiers (*) - + Select Files to Send using Kermit Sélectionner les fichiers à envoyer en utilisant Kermit - + Select Files to Send using Xmodem Sélectionner les fichiers à envoyer en utilisant Xmodem - + Save Received Files using Xmodem Enregistrer les fichiers reçus en utilisant Xmodem - + Select Files to Send using Ymodem Sélectionner les fichiers à envoyer en utilisant Ymodem - + Select Files to Send using Zmodem Sélectionner les fichiers à envoyer en utilisant Zmodem - + Select a script file Sélectionner un fichier de script - + Python Files (*.py);;All Files (*) Fichiers Python (*.py);;Tous les fichiers (*) - + Select color Sélectionner une couleur - + Are you sure to disconnect " Êtes-vous sûr de vouloir vous déconnecter de " - + " session? " session ? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Ce logiciel est un émulateur de terminal qui fournit une connexion shell sécurisée (SSH), une connexion telnet, une connexion de port série et d'autres fonctions. - + This software does not collect any personal information, and does not send any information to the server. Ce logiciel ne collecte aucune information personnelle et n'envoie aucune information au serveur. - + This software does not contain any malicious code, and does not contain any backdoors. Ce logiciel ne contient aucun code malveillant et ne contient aucune porte dérobée. - + This software is open source software, you can view the source code on the github website. Ce logiciel est un logiciel open source, vous pouvez consulter le code source sur le site web de github. - + This software is provided as is, without any warranty. Ce logiciel est fourni tel quel, sans aucune garantie. - + If you have any questions or suggestions, please contact the author. Si vous avez des questions ou des suggestions, veuillez contacter l'auteur. - + Version Version - + Commit Validation - + Date Date - - + + Author Auteur - + Website Site web - + Tab Onglet - + Arrange sessions in tabs Organiser les sessions dans des onglets - + Tile Mosaïque - + Arrange sessions in non-overlapping tiles Organiser les sessions dans des mosaïques non superposées - + Cascade Cascade - + Arrange sessions to overlap each other Organiser les sessions pour qu'elles se chevauchent - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light Clair - + Switch to light theme Passer au thème clair - + Dark Sombre - + Switch to dark theme Passer au thème sombre - + Display help Afficher l'aide - + Check Update Vérifier les mises à jour - + Check for updates Vérifier les mises à jour - - + + About À propos de - + Display about dialog Afficher la boîte de dialogue À propos de - + About Qt À propos de Qt - + Display about Qt dialog Afficher la boîte de dialogue À propos de Qt - + Plugin Info Informations sur le plugin - + Display plugin information dialog Afficher la boîte de dialogue d'informations sur le plugin - + PrintScreen saved to %1 PrintScreen enregistré dans %1 - + Save Screenshot Enregistrer la capture d'écran - + Image Files (*.jpg) Fichiers image (*.jpg) - - + + Screenshot saved to %1 Capture d'écran enregistrée dans %1 - + Save Session Export Enregistrer l'exportation de la session - + Text Files (*.txt);;HTML Files (*.html) Fichiers texte (*.txt);;Fichiers HTML (*.html) - + Text Files (*.txt) Fichiers texte (*.txt) - + HTML Files (*.html) Fichiers HTML (*.html) - + Session Export saved to %1 Exportation de la session enregistrée dans %1 - + Session Export failed to save to %1 Échec de l'enregistrement de l'exportation de la session dans %1 - + Select a directory Sélectionner un répertoire - + Select a bookmark Sélectionner un marque-page - + Are you sure to clean all bookmark? Êtes-vous sûr de vouloir nettoyer tous les marque-pages ? - + Port Port - + Video background is enabled, please enable animation in global options (more system resources) or change background image. L'arrière-plan vidéo est activé, veuillez activer l'animation dans les options globales (plus de ressources système) ou changer l'image d'arrière-plan. - + Session information get failed. Échec de l'obtention des informations de session. - + Telnet - Telnet - - + Telnet Telnet - + Serial - Série - - + Serial Série - + Raw - Brut - - + Raw Brut - + NamePipe - Tube nommé - - + NamePipe Tube nommé - - + + Local Shell Shell local - + Local Shell - Shell local - - + Global Shortcuts: Raccourcis globaux : - + show/hide menu bar Afficher/Masquer la barre de menu - + connect to LocalShell Se connecter à LocalShell - + clone current session Cloner la session actuelle - + switch ui to STD mode Passer l'interface utilisateur en mode STD - + switch ui to MINI mode Passer l'interface utilisateur en mode MINI - + switch to previous session Passer à la session précédente - + switch to next session Passer à la session suivante - + switch to session [num] Passer à la session [num] - + Go to line start Aller au début de la ligne - + Go to line end Aller à la fin de la ligne - + There are sessions that have not yet been unlocked, please unlock them first. Il y a des sessions qui n'ont pas encore été déverrouillées, veuillez les déverrouiller d'abord. - + Are you sure to quit? Êtes-vous sûr de vouloir quitter ? @@ -2707,8 +2708,8 @@ - - + + Warning Attention @@ -2745,7 +2746,7 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session - + The Default Local Shell is not a valid file! Le shell local par défaut n'est pas un fichier valide ! @@ -2795,7 +2796,7 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session Transfert - + The User Plugins Path is not a directory! Le chemin des plugins utilisateur n'est pas un répertoire ! @@ -2869,93 +2870,36 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session Commande interne - + Copy Copier - + Paste Coller - + Select All Tout sélectionner - + Find Rechercher - + Zoom In Agrandir - + Zoom Out Réduire - - Session - - - Bell in session '%1' - Sonnerie dans la session '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Taille : XXX x XXX - - - - Size: %1 x %2 - Taille : %1 x %2 - - - - Paste multiline text - Coller du texte multiligne - - - - Are you sure you want to paste this text? - Êtes-vous sûr de vouloir coller ce texte ? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>La sortie a été <a href="http://en.wikipedia.org/wiki/Flow_control">suspendue</a> en appuyant sur Ctrl+S. Appuyez sur <b>Ctrl+Q</b> pour reprendre.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Suivre le lien (ctrl + clic) - - - - Follow path (ctrl + click) - Suivre le chemin (ctrl + clic) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - Aucun traducteur de clavier disponible. Les informations nécessaires à la conversion des frappes de touches en caractères à envoyer au terminal sont manquantes. - - LockSessionWindow @@ -3484,47 +3428,47 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session QObject - + Un-named Color Scheme Schéma de couleur sans nom - + Accessible Color Scheme Schéma de couleur accessible - + Open Link Ouvrir le lien - + Copy Link Address Copier l'adresse du lien - + Send Email To... Envoyer un courriel à... - + Copy Email Address Copier l'adresse de courriel - + Open Path Ouvrir le chemin - + Open Containing Folder Ouvrir le dossier contenant - + Copy Path Copier le chemin @@ -3587,12 +3531,12 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session QTermWidget - + Color Scheme Error Erreur de schéma de couleur - + Cannot load color scheme: %1 Impossible de charger le schéma de couleur : %1 @@ -3897,20 +3841,20 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session Trouver : - - + + Match case Respecter la casse - - + + Regular expression Expression régulière - - + + Highlight all matches Surligner toutes les correspondances @@ -4252,25 +4196,25 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session SessionsWindow - + Telnet Error Erreur Telnet - + Telnet error: %1. Erreur Telnet : %1. - - + + Serial Error Erreur série - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session %1. - + Raw Socket Error Erreur de socket brut - + Raw Socket error: %1. Erreur de socket brut : %1. - + Name Pipe Error Erreur de tube nommé - + Name Pipe error: %1. Erreur de tube nommé : %1. - - + + SSH2 Error Erreur SSH2 - - + + SSH2 error: %1. Erreur SSH2 : %1. - - + + Open URL Ouvrir l'URL - - + + Cannot open URL %1. Impossible d'ouvrir l'URL %1. - + Select Files to Send using Zmodem Sélectionner les fichiers à envoyer en utilisant Zmodem - + All Files (*) Tous les fichiers (*) - + Start Local Shell Démarrer le shell local - + Cannot start local shell: %1. Impossible de démarrer le shell local : %1. - + Serial port %1 has been removed. Le port série %1 a été supprimé. - + Save log... Enregistrer le journal... - + log files (*.log) Fichiers journaux (*.log) - + Save log Enregistrer le journal - - - + + + Cannot write file %1: %2. Impossible d'écrire le fichier %1 : %2. - + Save Raw log... Enregistrer le journal brut... - + binary files (*.bin) Fichiers binaires (*.bin) - + Save Raw log Enregistrer le journal brut - + Unlock Session Déverrouiller la session - + Wrong password! Mot de passe incorrect ! - + Receive ASCII File Recevoir un fichier ASCII @@ -4662,6 +4606,34 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session Informations de transfert + + TerminalDisplay + + + Size: XXX x XXX + Taille : XXX x XXX + + + + Size: %1 x %2 + Taille : %1 x %2 + + + + Paste multiline text + Coller du texte multiligne + + + + Are you sure you want to paste this text? + Êtes-vous sûr de vouloir coller ce texte ? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>La sortie a été <a href="http://en.wikipedia.org/wiki/Flow_control">suspendue</a> en appuyant sur Ctrl+S. Appuyez sur <b>Ctrl+Q</b> pour reprendre.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ Si vous avez besoin d'utiliser un autre shell, veuillez créer une session Écraser %1 caractères + + UrlFilter + + + Follow link (ctrl + click) + Suivre le lien (ctrl + clic) + + + + Follow path (ctrl + click) + Suivre le chemin (ctrl + clic) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Aucun traducteur de clavier disponible. Les informations nécessaires à la conversion des frappes de touches en caractères à envoyer au terminal sont manquantes. + + keyMapManager diff --git a/lang/quardCRT_ja_JP.ts b/lang/quardCRT_ja_JP.ts index 5dd30fde..f47805cf 100644 --- a/lang/quardCRT_ja_JP.ts +++ b/lang/quardCRT_ja_JP.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar ツールバー @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning 警告 @@ -285,7 +285,7 @@ - + Ready 準備完了 @@ -464,7 +464,7 @@ - + Help ヘルプ @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect 接続するホストを入力 <Alt+R> - + Disconnect All 全て切断 - + Disconnect all sessions 全てのセッションを切断 - + Clone Session セッションを複製 - + Clone current session <Ctrl+Shift+T> 現在のセッションを複製 <Ctrl+Shift+T> @@ -595,564 +596,564 @@ セッションをロック - + Log Session セッションを記録 - + Create a log file for current session 現在のセッションを記録 - + Raw Log Session セッションを生記録 - + Create a raw log file for current session 現在のセッションを生記録 - + Hex View 16進数ビュー - + Show/Hide Hex View for current session 現在のセッションの16進数ビューを表示/非表示 - + Exit 終了 - + Quit the application アプリケーションを終了 - + Copy コピー - + Copy the selected text to the clipboard <Command+C> 選択したテキストをクリップボードにコピー <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> 選択したテキストをクリップボードにコピー <Ctrl+Ins> - + Paste 貼り付け - + Paste the clipboard text to the current session <Command+V> クリップボードのテキストを現在のセッションに貼り付け <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> クリップボードのテキストを現在のセッションに貼り付け <Shift+Ins> - + Copy and Paste コピーと貼り付け - + Copy the selected text to the clipboard and paste to the current session 選択したテキストをクリップボードにコピーして現在のセッションに貼り付け - + Select All 全て選択 - + Select all text in the current session <Ctrl+Shift+A> 現在のセッションの全てのテキストを選択 <Ctrl+Shift+A> - + Find... 検索... - + Find text in the current session <Ctrl+F> 現在のセッションのテキストを検索 <Ctrl+F> - + Print Screen プリントスクリーン - + Print current screen 現在のスクリーンを印刷 - + Screen Shot スクリーンショット - + Screen shot current screen <Alt+P> 現在の画面をスクリーンショット <Alt+P> - + Session Export セッションをエクスポート - + Export current session to a file <Alt+O> 現在のセッションをファイルにエクスポート <Alt+O> - + Clear Scrollback スクロールバックをクリア - + Clear the contents of the scrollback rows スクロールバックの内容をクリア - + Clear Screen 画面をクリア - + Clear the contents of the current screen 現在の画面の内容をクリア - + Clear Screen and Scrollback 画面とスクロールバックをクリア - + Clear the contents of the screen and scrollback 画面とスクロールバックの内容をクリア - + Reset リセット - + Reset terminal emulator 端末エミュレータをリセット - + Zoom In 拡大 - + Zoom In <Ctrl+"="> 拡大 <Ctrl+"="> - + Zoom Out 縮小 - + Zoom Out <Ctrl+"-"> 縮小 <Ctrl+"-"> - - + + Zoom Reset ズームリセット - + Layout レイアウト - + Single Layout シングルレイアウト - + Single layout シングルレイアウト - + Two Columns Layout 2列レイアウト - + Two columns layout 2列レイアウト - + Three Columns Layout 3列レイアウト - + Three columns layout 3列レイアウト - + Two Rows Layout 2行レイアウト - + Two rows layout 2行レイアウト - + Three Rows Layout 3行レイアウト - + Three rows layout 3行レイアウト - + Grid Layout グリッドレイアウト - + Grid layout グリッドレイアウト - + Two Rows Right Layout 2行右レイアウト - + Two rows right layout 2行右レイアウト - + Two Columns Bottom Layout 2列下レイアウト - + Two columns bottom layout 2列下レイアウト - + Flip Layout レイアウトを反転 - + Flip layout レイアウトを反転 - + Menu Bar メニューバー - + Show/Hide Menu Bar <Alt+U> メニューバーを表示/非表示 <Alt+U> - + Show/Hide Tool Bar ツールバーを表示/非表示 - + Status Bar ステータスバー - + Show/Hide Status Bar ステータスバーを表示/非表示 - + Command Window コマンドウィンドウ - + Show/Hide Command Window コマンドウィンドウを表示/非表示 - + Connect Bar 接続バー - + Show/Hide Connect Bar 接続バーを表示/非表示 - + Side Window サイドウィンドウ - + Show/Hide Side Window サイドウィンドウを表示/非表示 - + Windows Transparency ウィンドウの透明度 - + Enable/Disable alpha transparency アルファ透明度を有効/無効 - + Vertical Scroll Bar 垂直スクロールバー - + Show/Hide Vertical Scroll Bar 垂直スクロールバーを表示/非表示 - + Allways On Top 常に最前面に表示 - + Show window always on top ウィンドウを常に最前面に表示 - + Full Screen 全画面表示 - + Toggle between full screen and normal mode <Alt+Enter> 全画面表示と通常表示を切り替え <Alt+Enter> - + Session Options... セッションオプション... - + Configure session options セッションオプションを設定 - + Global Options... グローバルオプション... - + Configure global options グローバルオプションを設定 - + Real-time Save Options リアルタイム保存設定 - + Real-time save session options and global options セッションオプションとグローバルオプションをリアルタイムで保存 - + Save Settings Now 設定を保存 - + Save options configuration now オプション設定を保存 - + Send ASCII... ASCII送信... - + Send ASCII file ASCIIファイルを送信 - + Receive ASCII... ASCII受信... - + Receive ASCII file ASCIIファイルを受信 - + Send Binary... バイナリ送信... - + Send Binary file バイナリファイルを送信 - + Send Kermit... Kermit送信... - + Send a file using Kermit Kermitでファイルを送信 - + Receive Kermit... Kermit受信... - + Receive a file using Kermit Kermitでファイルを受信 - + Send Xmodem... Xmodem送信... - + Send a file using Xmodem Xmodemでファイルを送信 - + Receive Xmodem... Xmodem受信... - + Receive a file using Xmodem Xmodemでファイルを受信 - + Send Ymodem... Ymodem送信... - + Send a file using Ymodem Ymodemでファイルを送信 - + Receive Ymodem... Ymodem受信... - + Receive a file using Ymodem Ymodemでファイルを受信 - + Zmodem Upload List... Zmodemアップロードリスト... - + Display Zmodem file upload list Zmodemファイルアップロードリストを表示 - + Start Zmodem Upload Zmodemアップロード開始 - + Start Zmodem file upload Zmodemファイルアップロードを開始 - + Start TFTP Server TFTPサーバー開始 - + Start/Stop the TFTP server TFTPサーバーを開始/停止 - + Run... 実行... - + Run a script スクリプトを実行 - + Cancel キャンセル @@ -1213,759 +1214,759 @@ 色を変更 - + Cancel script execution スクリプト実行をキャンセル - + Start Recording Script スクリプト記録開始 - + Start recording script スクリプト記録を開始 - + Stop Recording Script... スクリプト記録停止... - + Stop recording script スクリプト記録を停止 - + Cancel Recording Script スクリプト記録キャンセル - + Cancel recording script スクリプト記録をキャンセル - + Add Bookmark ブックマークを追加 - + Add a bookmark ブックマークを追加 - - + + Remove Bookmark ブックマークを削除 - + Remove a bookmark ブックマークを削除 - - + + Clean All Bookmark 全てのブックマークをクリア - + Clean all bookmark 全てのブックマークをクリア - + Keymap Manager キーマップマネージャー - + Display keymap editor キーマップエディターを表示 - + Create Public Key... 公開鍵を作成... - + Create a public key 公開鍵を作成 - + Publickey Manager 公開鍵マネージャー - + Display publickey manager 公開鍵マネージャーを表示 - + Internal Command 内部コマンド - + Display Internal Command window 内部コマンドウィンドウを表示 - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color テーマカラー - + Set theme color, cancel to use default テーマカラーを設定、デフォルトを使用するにはキャンセル - - + + Keyborad Shortcuts Reference キーボードショートカットリファレンス - + Display keyborad shortcuts reference キーボードショートカットリファレンスを表示 - - + + Privacy Statement プライバシーステートメント - + Display privacy statement プライバシーステートメントを表示 - - + + About Python Pythonについて - + Display about Python dialog Pythonについてのダイアログを表示 - + Laboratory 実験室 - - + + SSH Scanning SSHスキャン - + Display SSH scanning dialog SSHスキャンダイアログを表示 - + Plugin metaData not found! プラグインのメタデータが見つかりません! - + Plugin api version not found! プラグインAPIバージョンが見つかりません! - + Plugin api version not match! プラグインAPIバージョンが一致しません! - + Plugin menu not found! プラグインメニューが見つかりません! - + Plugin init failed! プラグインの初期化に失敗しました! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! ブロードキャストセッションはファイルを転送できません! - + Select Files to Send as ASCII ASCIIとして送信するファイルを選択 - - + + Text Files (*.txt);;All Files (*) テキストファイル (*.txt);;全てのファイル (*) - + Save Received Data as ASCII 受信データをASCIIとして保存 - + Select Files to Send as BINARY バイナリとして送信するファイルを選択 - - - - - - + + + + + + All Files (*) 全てのファイル (*) - + Select Files to Send using Kermit Kermitを使用して送信するファイルを選択 - + Select Files to Send using Xmodem Xmodemを使用して送信するファイルを選択 - + Save Received Files using Xmodem Xmodemを使用して受信したファイルを保存 - + Select Files to Send using Ymodem Ymodemを使用して送信するファイルを選択 - + Select Files to Send using Zmodem Zmodemを使用して送信するファイルを選択 - + Select a script file スクリプトファイルを選択 - + Python Files (*.py);;All Files (*) Pythonファイル (*.py);;全てのファイル (*) - + Select color 色を選択 - + Are you sure to disconnect " 本当に切断しますか" - + " session? " セッション? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. このソフトウェアは、セキュアシェル(SSH)接続、telnet接続、シリアルポート接続などを提供する端末エミュレータです。 - + This software does not collect any personal information, and does not send any information to the server. このソフトウェアは個人情報を収集せず、サーバーに情報を送信しません。 - + This software does not contain any malicious code, and does not contain any backdoors. このソフトウェアには悪意のあるコードは含まれておらず、バックドアも含まれていません。 - + This software is open source software, you can view the source code on the github website. このソフトウェアはオープンソースソフトウェアです。ソースコードはgithubのウェブサイトで閲覧できます。 - + This software is provided as is, without any warranty. このソフトウェアは無保証で提供されます。 - + If you have any questions or suggestions, please contact the author. 質問や提案がある場合は、作者に連絡してください。 - + Version バージョン - + Commit コミット - + Date 日付 - - + + Author 作者 - + Website ウェブサイト - + Tab タブ - + Arrange sessions in tabs セッションをタブで表示 - + Tile タイル - + Arrange sessions in non-overlapping tiles セッションを重ならないようにタイルで表示 - + Cascade カスケード - + Arrange sessions to overlap each other セッションを重ねて表示 - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light 明るい - + Switch to light theme 明るいテーマに切り替える - + Dark 暗い - + Switch to dark theme 暗いテーマに切り替える - + Display help ヘルプを表示 - + Check Update 更新をチェック - + Check for updates 更新をチェック - - + + About について - + Display about dialog についてのダイアログを表示 - + About Qt Qtについて - + Display about Qt dialog Qtについてのダイアログを表示 - + Plugin Info プラグイン情報 - + Display plugin information dialog プラグイン情報ダイアログを表示 - + PrintScreen saved to %1 プリントスクリーンを %1 に保存 - + Save Screenshot スクリーンショットを保存 - + Image Files (*.jpg) 画像ファイル (*.jpg) - - + + Screenshot saved to %1 スクリーンショットを %1 に保存 - + Save Session Export セッションエクスポートを保存 - + Text Files (*.txt);;HTML Files (*.html) テキストファイル (*.txt);;HTMLファイル (*.html) - + Text Files (*.txt) テキストファイル (*.txt) - + HTML Files (*.html) HTMLファイル (*.html) - + Session Export saved to %1 セッションエクスポートを %1 に保存 - + Session Export failed to save to %1 セッションエクスポートを %1 に保存できませんでした - + Select a directory ディレクトリを選択 - + Select a bookmark ブックマークを選択 - + Are you sure to clean all bookmark? 全てのブックマークをクリアしてもよろしいですか? - + Port ポート - + Video background is enabled, please enable animation in global options (more system resources) or change background image. ビデオ背景が有効になっています。グローバルオプションでアニメーションを有効にするか、背景画像を変更してください(システムリソースが増えます)。 - + Session information get failed. セッション情報の取得に失敗しました。 - + Telnet - - + Telnet - + Serial - シリアル - - + Serial シリアル - + Raw - - + Raw - + NamePipe - 名前付きパイプ - - + NamePipe 名前付きパイプ - - + + Local Shell ローカル端末 - + Local Shell - ローカル端末 - - + Global Shortcuts: グローバルショートカット: - + show/hide menu bar メニューバーを表示/非表示 - + connect to LocalShell ローカル端末に接続 - + clone current session 現在のセッションを複製 - + switch ui to STD mode UIを標準モードに切り替え - + switch ui to MINI mode UIをミニモードに切り替え - + switch to previous session 前のセッションに切り替え - + switch to next session 次のセッションに切り替え - + switch to session [num] セッション[num]に切り替え - + Go to line start 行頭に移動 - + Go to line end 行末に移動 - + There are sessions that have not yet been unlocked, please unlock them first. ロックされていないセッションがあります。まずロックを解除して下さい。 - + Are you sure to quit? 終了してもよろしいですか? @@ -2697,8 +2698,8 @@ - - + + Warning 警告 @@ -2735,7 +2736,7 @@ PowerShell 5以降を使用してください! - + The Default Local Shell is not a valid file! デフォルトのローカル端末は有効なファイルではありません! @@ -2785,7 +2786,7 @@ PowerShell 5以降を使用してください! 転送 - + The User Plugins Path is not a directory! ユーザープラグインのパスはディレクトリではありません! @@ -2869,93 +2870,36 @@ PowerShell 5以降を使用してください! 内部コマンド - + Copy コピー - + Paste 貼り付け - + Select All 全て選択 - + Find 検索 - + Zoom In 拡大 - + Zoom Out 縮小 - - Session - - - Bell in session '%1' - セッション '%1' でベル - - - - TerminalDisplay - - - Size: XXX x XXX - サイズ: XXX x XXX - - - - Size: %1 x %2 - サイズ: %1 x %2 - - - - Paste multiline text - 複数行のテキストを貼り付ける - - - - Are you sure you want to paste this text? - このテキストを貼り付けてもよろしいですか? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>Ctrl+Sを押すと出力が<a href="http://en.wikipedia.org/wiki/Flow_control">中断</a>されます。再開するには<b>Ctrl+Q</b>を押して下さい。</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - リンクを開く (ctrl + click) - - - - Follow path (ctrl + click) - パスを開く (ctrl + click) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - キーボード変換がありません。キー入力を端末に送信するための情報がありません。 - - LockSessionWindow @@ -3484,47 +3428,47 @@ PowerShell 5以降を使用してください! QObject - + Un-named Color Scheme 名前のないカラースキーム - + Accessible Color Scheme アクセシブルカラースキーム - + Open Link リンクを開く - + Copy Link Address リンクアドレスをコピー - + Send Email To... メールを送信... - + Copy Email Address メールアドレスをコピー - + Open Path パスを開く - + Open Containing Folder 含まれるフォルダを開く - + Copy Path パスをコピー @@ -3587,12 +3531,12 @@ PowerShell 5以降を使用してください! QTermWidget - + Color Scheme Error カラースキームエラー - + Cannot load color scheme: %1 カラースキームを読み込めません: %1 @@ -3897,20 +3841,20 @@ PowerShell 5以降を使用してください! 検索: - - + + Match case 大文字と小文字を区別する - - + + Regular expression 正規表現 - - + + Highlight all matches 全ての一致箇所をハイライトする @@ -4252,25 +4196,25 @@ PowerShell 5以降を使用してください! SessionsWindow - + Telnet Error TELNETエラー - + Telnet error: %1. TELNETエラー: %1. - - + + Serial Error シリアルエラー - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ PowerShell 5以降を使用してください! %1. - + Raw Socket Error 生ソケットエラー - + Raw Socket error: %1. 生ソケットエラー: %1. - + Name Pipe Error 名前付きパイプエラー - + Name Pipe error: %1. 名前付きパイプエラー: %1. - - + + SSH2 Error SSH2エラー - - + + SSH2 error: %1. SSH2エラー: %1. - - + + Open URL URLを開く - - + + Cannot open URL %1. URL %1 を開けません。 - + Select Files to Send using Zmodem Zmodemを使用して送信するファイルを選択 - + All Files (*) 全てのファイル (*) - + Start Local Shell ローカル端末を開始 - + Cannot start local shell: %1. ローカル端末を開始できません: %1. - + Serial port %1 has been removed. シリアルポート %1 が削除されました。 - + Save log... ログを保存... - + log files (*.log) ログファイル (*.log) - + Save log ログを保存 - - - + + + Cannot write file %1: %2. ファイル %1 に書き込めません: %2. - + Save Raw log... 生ログを保存... - + binary files (*.bin) バイナリファイル (*.bin) - + Save Raw log 生ログを保存 - + Unlock Session セッションをアンロック - + Wrong password! パスワードが間違っています! - + Receive ASCII File ASCIIファイルを受信 @@ -4662,6 +4606,34 @@ PowerShell 5以降を使用してください! 転送情報 + + TerminalDisplay + + + Size: XXX x XXX + サイズ: XXX x XXX + + + + Size: %1 x %2 + サイズ: %1 x %2 + + + + Paste multiline text + 複数行のテキストを貼り付ける + + + + Are you sure you want to paste this text? + このテキストを貼り付けてもよろしいですか? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Ctrl+Sを押すと出力が<a href="http://en.wikipedia.org/wiki/Flow_control">中断</a>されます。再開するには<b>Ctrl+Q</b>を押して下さい。</qt> + + UndoStack @@ -4680,6 +4652,27 @@ PowerShell 5以降を使用してください! %1 文字を上書き + + UrlFilter + + + Follow link (ctrl + click) + リンクを開く (ctrl + click) + + + + Follow path (ctrl + click) + パスを開く (ctrl + click) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + キーボード変換がありません。キー入力を端末に送信するための情報がありません。 + + keyMapManager diff --git a/lang/quardCRT_ko_KR.ts b/lang/quardCRT_ko_KR.ts index 3f9bf470..63864961 100644 --- a/lang/quardCRT_ko_KR.ts +++ b/lang/quardCRT_ko_KR.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar 툴바 @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning 경고 @@ -285,7 +285,7 @@ - + Ready 준비 완료 @@ -464,7 +464,7 @@ - + Help 도움말 @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect 연결할 호스트 입력 <Alt+R> - + Disconnect All 모두 연결 해제 - + Disconnect all sessions 모든 세션 연결 해제 - + Clone Session 세션 복제 - + Clone current session <Ctrl+Shift+T> 현재 세션 복제 <Ctrl+Shift+T> @@ -595,564 +596,564 @@ 세션 잠금 - + Log Session 세션 로그 - + Create a log file for current session 현재 세션의 로그 파일 생성 - + Raw Log Session 세션 로그(원본) - + Create a raw log file for current session 현재 세션의 원본 로그 파일 생성 - + Hex View 16진수 보기 - + Show/Hide Hex View for current session 현재 세션의 16진수 보기 표시/숨기기 - + Exit 종료 - + Quit the application 애플리케이션 종료 - + Copy 복사 - + Copy the selected text to the clipboard <Command+C> 선택한 텍스트를 클립보드에 복사 <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> 선택한 텍스트를 클립보드에 복사 <Ctrl+Ins> - + Paste 붙여넣기 - + Paste the clipboard text to the current session <Command+V> 클립보드 텍스트를 현재 세션에 붙여넣기 <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> 클립보드 텍스트를 현재 세션에 붙여넣기 <Shift+Ins> - + Copy and Paste 복사 및 붙여넣기 - + Copy the selected text to the clipboard and paste to the current session 선택한 텍스트를 클립보드에 복사하고 현재 세션에 붙여넣기 - + Select All 모두 선택 - + Select all text in the current session <Ctrl+Shift+A> 현재 세션의 모든 텍스트 선택 <Ctrl+Shift+A> - + Find... 찾기... - + Find text in the current session <Ctrl+F> 현재 세션에서 텍스트 찾기 <Ctrl+F> - + Print Screen 스크린 샷 - + Print current screen 현재 화면 인쇄 - + Screen Shot 스크린 샷 - + Screen shot current screen <Alt+P> 현재 화면 스크린 샷 <Alt+P> - + Session Export 세션 내보내기 - + Export current session to a file <Alt+O> 현재 세션을 파일로 내보내기 <Alt+O> - + Clear Scrollback 스크롤백 지우기 - + Clear the contents of the scrollback rows 스크롤백 행의 내용 지우기 - + Clear Screen 화면 지우기 - + Clear the contents of the current screen 현재 화면의 내용 지우기 - + Clear Screen and Scrollback 화면과 스크롤백 지우기 - + Clear the contents of the screen and scrollback 화면과 스크롤백의 내용 지우기 - + Reset 재설정 - + Reset terminal emulator 터미널 에뮬레이터 재설정 - + Zoom In 확대 - + Zoom In <Ctrl+"="> 확대 <Ctrl+"="> - + Zoom Out 축소 - + Zoom Out <Ctrl+"-"> 축소 <Ctrl+"-"> - - + + Zoom Reset 확대/축소 초기화 - + Layout 레이아웃 - + Single Layout 단일 레이아웃 - + Single layout 단일 레이아웃 - + Two Columns Layout 두 열 레이아웃 - + Two columns layout 두 열 레이아웃 - + Three Columns Layout 세 열 레이아웃 - + Three columns layout 세 열 레이아웃 - + Two Rows Layout 두 행 레이아웃 - + Two rows layout 두 행 레이아웃 - + Three Rows Layout 세 행 레이아웃 - + Three rows layout 세 행 레이아웃 - + Grid Layout 그리드 레이아웃 - + Grid layout 그리드 레이아웃 - + Two Rows Right Layout 오른쪽 두 행 레이아웃 - + Two rows right layout 오른쪽 두 행 레이아웃 - + Two Columns Bottom Layout 아래쪽 두 열 레이아웃 - + Two columns bottom layout 아래쪽 두 열 레이아웃 - + Flip Layout 레이아웃 뒤집기 - + Flip layout 레이아웃 뒤집기 - + Menu Bar 메뉴 바 - + Show/Hide Menu Bar <Alt+U> 메뉴 바 표시/숨기기 <Alt+U> - + Show/Hide Tool Bar 툴바 표시/숨기기 - + Status Bar 상태 바 - + Show/Hide Status Bar 상태 바 표시/숨기기 - + Command Window 명령 창 - + Show/Hide Command Window 명령 창 표시/숨기기 - + Connect Bar 연결 바 - + Show/Hide Connect Bar 연결 바 표시/숨기기 - + Side Window 사이드 창 - + Show/Hide Side Window 사이드 창 표시/숨기기 - + Windows Transparency 창 투명도 - + Enable/Disable alpha transparency 알파 투명도 사용/사용 안 함 - + Vertical Scroll Bar 수직 스크롤 바 - + Show/Hide Vertical Scroll Bar 수직 스크롤 바 표시/숨기기 - + Allways On Top 항상 위에 표시 - + Show window always on top 창을 항상 위에 표시 - + Full Screen 전체 화면 - + Toggle between full screen and normal mode <Alt+Enter> 전체 화면 모드와 일반 모드 전환 <Alt+Enter> - + Session Options... 세션 옵션... - + Configure session options 세션 옵션 구성 - + Global Options... 전역 옵션... - + Configure global options 전역 옵션 구성 - + Real-time Save Options 실시간 저장 옵션 - + Real-time save session options and global options 세션 옵션과 전역 옵션을 실시간으로 저장 - + Save Settings Now 설정 지금 저장 - + Save options configuration now 옵션 구성 지금 저장 - + Send ASCII... ASCII 전송... - + Send ASCII file ASCII 파일 전송 - + Receive ASCII... ASCII 수신... - + Receive ASCII file ASCII 파일 수신 - + Send Binary... 바이너리 전송... - + Send Binary file 바이너리 파일 전송 - + Send Kermit... Kermit 전송... - + Send a file using Kermit Kermit을 사용하여 파일 전송 - + Receive Kermit... Kermit 수신... - + Receive a file using Kermit Kermit을 사용하여 파일 수신 - + Send Xmodem... Xmodem 전송... - + Send a file using Xmodem Xmodem을 사용하여 파일 전송 - + Receive Xmodem... Xmodem 수신... - + Receive a file using Xmodem Xmodem을 사용하여 파일 수신 - + Send Ymodem... Ymodem 전송... - + Send a file using Ymodem Ymodem을 사용하여 파일 전송 - + Receive Ymodem... Ymodem 수신... - + Receive a file using Ymodem Ymodem을 사용하여 파일 수신 - + Zmodem Upload List... Zmodem 파일 업로드 목록... - + Display Zmodem file upload list Zmodem 파일 업로드 목록 표시 - + Start Zmodem Upload Zmodem 파일 업로드 시작 - + Start Zmodem file upload Zmodem 파일 업로드 시작 - + Start TFTP Server TFTP 서버 시작 - + Start/Stop the TFTP server TFTP 서버 시작/중지 - + Run... 실행... - + Run a script 스크립트 실행 - + Cancel 취소 @@ -1213,759 +1214,759 @@ 색상 변경 - + Cancel script execution 스크립트 실행 취소 - + Start Recording Script 스크립트 녹화 시작 - + Start recording script 스크립트 녹화 시작 - + Stop Recording Script... 스크립트 녹화 중지... - + Stop recording script 스크립트 녹화 중지 - + Cancel Recording Script 스크립트 녹화 취소 - + Cancel recording script 스크립트 녹화 취소 - + Add Bookmark 북마크 추가 - + Add a bookmark 북마크 추가 - - + + Remove Bookmark 북마크 제거 - + Remove a bookmark 북마크 제거 - - + + Clean All Bookmark 모든 북마크 지우기 - + Clean all bookmark 모든 북마크 지우기 - + Keymap Manager 키맵 관리자 - + Display keymap editor 키맵 편집기 표시 - + Create Public Key... 공개 키 생성... - + Create a public key 공개 키 생성 - + Publickey Manager 공개 키 관리자 - + Display publickey manager 공개 키 관리자 표시 - + Internal Command 내부 명령 - + Display Internal Command window 내부 명령 창 표시 - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color 테마 색상 - + Set theme color, cancel to use default 테마 색상 설정, 기본값 사용하려면 취소 - - + + Keyborad Shortcuts Reference 키보드 단축키 참조 - + Display keyborad shortcuts reference 키보드 단축키 참조 표시 - - + + Privacy Statement 개인 정보 보호 정책 - + Display privacy statement 개인 정보 보호 정책 표시 - - + + About Python Python 정보 - + Display about Python dialog Python 정보 대화 상자 표시 - + Laboratory 실험실 - - + + SSH Scanning SSH 스캔 - + Display SSH scanning dialog SSH 스캔 대화 상자 표시 - + Plugin metaData not found! 플러그인 메타데이터를 찾을 수 없습니다! - + Plugin api version not found! 플러그인 API 버전을 찾을 수 없습니다! - + Plugin api version not match! 플러그인 API 버전이 일치하지 않습니다! - + Plugin menu not found! 플러그인 메뉴를 찾을 수 없습니다! - + Plugin init failed! 플러그인 초기화 실패! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! 브로드캐스트 세션은 파일을 전송할 수 없습니다! - + Select Files to Send as ASCII ASCII로 전송할 파일 선택 - - + + Text Files (*.txt);;All Files (*) 텍스트 파일 (*.txt);;모든 파일 (*) - + Save Received Data as ASCII 수신된 데이터를 ASCII로 저장 - + Select Files to Send as BINARY 바이너리로 전송할 파일 선택 - - - - - - + + + + + + All Files (*) 모든 파일 (*) - + Select Files to Send using Kermit Kermit을 사용하여 전송할 파일 선택 - + Select Files to Send using Xmodem Xmodem을 사용하여 전송할 파일 선택 - + Save Received Files using Xmodem Xmodem을 사용하여 수신된 파일 저장 - + Select Files to Send using Ymodem Ymodem을 사용하여 전송할 파일 선택 - + Select Files to Send using Zmodem Zmodem을 사용하여 전송할 파일 선택 - + Select a script file 스크립트 파일 선택 - + Python Files (*.py);;All Files (*) Python 파일 (*.py);;모든 파일 (*) - + Select color 색상 선택 - + Are you sure to disconnect " 를 연결 해제하시겠습니까? " - + " session? " 세션? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. 이 소프트웨어는 안전한 셸 (SSH) 연결, 텔넷 연결, 시리얼 포트 연결 및 기타 기능을 제공하는 터미널 에뮬레이터입니다. - + This software does not collect any personal information, and does not send any information to the server. 이 소프트웨어는 개인 정보를 수집하지 않으며 서버로 정보를 전송하지 않습니다. - + This software does not contain any malicious code, and does not contain any backdoors. 이 소프트웨어에는 악성 코드가 포함되어 있지 않으며 백도어도 포함되어 있지 않습니다. - + This software is open source software, you can view the source code on the github website. 이 소프트웨어는 오픈 소스 소프트웨어이며, 소스 코드를 github 웹사이트에서 볼 수 있습니다. - + This software is provided as is, without any warranty. 이 소프트웨어는 어떠한 보증도 없이 제공됩니다. - + If you have any questions or suggestions, please contact the author. 질문이나 제안 사항이 있으면 작성자에게 문의하십시오. - + Version 버전 - + Commit 커밋 - + Date 날짜 - - + + Author 작성자 - + Website 웹사이트 - + Tab - + Arrange sessions in tabs 탭에 세션 정렬 - + Tile 타일 - + Arrange sessions in non-overlapping tiles 겹치지 않는 타일에 세션 정렬 - + Cascade 계단식 - + Arrange sessions to overlap each other 서로 겹치도록 세션 정렬 - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light 밝게 - + Switch to light theme 밝은 테마로 전환 - + Dark 어둡게 - + Switch to dark theme 어두운 테마로 전환 - + Display help 도움말 표시 - + Check Update 업데이트 확인 - + Check for updates 업데이트 확인 - - + + About 정보 - + Display about dialog 정보 대화 상자 표시 - + About Qt Qt 정보 - + Display about Qt dialog Qt 정보 대화 상자 표시 - + Plugin Info 플러그인 정보 - + Display plugin information dialog 플러그인 정보 대화 상자 표시 - + PrintScreen saved to %1 스크린 샷 저장 위치: %1 - + Save Screenshot 스크린 샷 저장 - + Image Files (*.jpg) 이미지 파일 (*.jpg) - - + + Screenshot saved to %1 스크린 샷 저장 위치: %1 - + Save Session Export 세션 내보내기 저장 - + Text Files (*.txt);;HTML Files (*.html) 텍스트 파일 (*.txt);;HTML 파일 (*.html) - + Text Files (*.txt) 텍스트 파일 (*.txt) - + HTML Files (*.html) HTML 파일 (*.html) - + Session Export saved to %1 세션 내보내기 저장 위치: %1 - + Session Export failed to save to %1 세션 내보내기 저장 위치: %1 - + Select a directory 디렉터리 선택 - + Select a bookmark 북마크 선택 - + Are you sure to clean all bookmark? 모든 북마크를 지우시겠습니까? - + Port 포트 - + Video background is enabled, please enable animation in global options (more system resources) or change background image. 비디오 배경이 활성화되었습니다. 전역 옵션에서 애니메이션을 활성화하거나(시스템 리소스가 더 필요함) 배경 이미지를 변경하십시오. - + Session information get failed. 세션 정보 가져오기 실패. - + Telnet - - + Telnet 텔넷 - + Serial - 시리얼 - - + Serial 시리얼 - + Raw - Raw - - + Raw Raw - + NamePipe - 네임 파이프 - - + NamePipe 네임 파이프 - - + + Local Shell 로컬 쉘 - + Local Shell - 로컬 쉘 - - + Global Shortcuts: 전역 단축키: - + show/hide menu bar 메뉴 바 표시/숨기기 - + connect to LocalShell 로컬 쉘에 연결 - + clone current session 현재 세션 복제 - + switch ui to STD mode STD 모드로 UI 전환 - + switch ui to MINI mode MINI 모드로 UI 전환 - + switch to previous session 이전 세션으로 전환 - + switch to next session 다음 세션으로 전환 - + switch to session [num] 세션 [num]으로 전환 - + Go to line start 줄 시작으로 이동 - + Go to line end 줄 끝으로 이동 - + There are sessions that have not yet been unlocked, please unlock them first. 아직 잠금 해제되지 않은 세션이 있습니다. 먼저 잠금을 해제하십시오. - + Are you sure to quit? 종료하시겠습니까? @@ -2707,8 +2708,8 @@ - - + + Warning 경고 @@ -2745,7 +2746,7 @@ PowerShell 5 이상을 사용하십시오! - + The Default Local Shell is not a valid file! 기본 로컬 쉘이 유효한 파일이 아닙니다! @@ -2795,7 +2796,7 @@ PowerShell 5 이상을 사용하십시오! 전송 - + The User Plugins Path is not a directory! 사용자 플러그인 경로가 디렉터리가 아닙니다! @@ -2869,93 +2870,36 @@ PowerShell 5 이상을 사용하십시오! 내부 명령어 - + Copy 복사 - + Paste 붙여넣기 - + Select All 모두 선택 - + Find 찾기 - + Zoom In 확대 - + Zoom Out 축소 - - Session - - - Bell in session '%1' - '%1' 세션에서 벨 - - - - TerminalDisplay - - - Size: XXX x XXX - 크기: XXX x XXX - - - - Size: %1 x %2 - 크기: %1 x %2 - - - - Paste multiline text - 여러 줄 텍스트 붙여넣기 - - - - Are you sure you want to paste this text? - 이 텍스트를 붙여넣으시겠습니까? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>Ctrl+S를 눌러 출력이 <a href="http://en.wikipedia.org/wiki/Flow_control">중지</a>되었습니다. 재개하려면 <b>Ctrl+Q</b>를 누르십시오.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - 링크 따라가기 (ctrl + 클릭) - - - - Follow path (ctrl + click) - 경로 따라가기 (ctrl + 클릭) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - 사용 가능한 키보드 변환기가 없습니다. 키를 문자로 변환하여 터미널로 보내는 데 필요한 정보가 없습니다. - - LockSessionWindow @@ -3484,47 +3428,47 @@ PowerShell 5 이상을 사용하십시오! QObject - + Un-named Color Scheme 이름 없는 색상 구성표 - + Accessible Color Scheme 접근 가능한 색상 구성표 - + Open Link 링크 열기 - + Copy Link Address 링크 주소 복사 - + Send Email To... 이메일 보내기... - + Copy Email Address 이메일 주소 복사 - + Open Path 경로 열기 - + Open Containing Folder 폴더 열기 - + Copy Path 경로 복사 @@ -3587,12 +3531,12 @@ PowerShell 5 이상을 사용하십시오! QTermWidget - + Color Scheme Error 색상 구성표 오류 - + Cannot load color scheme: %1 색상 구성표를 불러올 수 없습니다: %1 @@ -3897,20 +3841,20 @@ PowerShell 5 이상을 사용하십시오! 찾기: - - + + Match case 대소문자 구분 - - + + Regular expression 정규식 - - + + Highlight all matches 모든 일치 항목 강조 표시 @@ -4252,25 +4196,25 @@ PowerShell 5 이상을 사용하십시오! SessionsWindow - + Telnet Error 텔넷 오류 - + Telnet error: %1. 텔넷 오류: %1. - - + + Serial Error 시리얼 오류 - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ PowerShell 5 이상을 사용하십시오! %1. - + Raw Socket Error Raw 소켓 오류 - + Raw Socket error: %1. Raw 소켓 오류: %1. - + Name Pipe Error 네임 파이프 오류 - + Name Pipe error: %1. 네임 파이프 오류: %1. - - + + SSH2 Error SSH2 오류 - - + + SSH2 error: %1. SSH2 오류: %1. - - + + Open URL URL 열기 - - + + Cannot open URL %1. %1 URL을 열 수 없습니다. - + Select Files to Send using Zmodem Zmodem을 사용하여 전송할 파일 선택 - + All Files (*) 모든 파일 (*) - + Start Local Shell 로컬 쉘 시작 - + Cannot start local shell: %1. 로컬 쉘을 시작할 수 없습니다: %1. - + Serial port %1 has been removed. 시리얼 포트 %1이 제거되었습니다. - + Save log... 로그 저장... - + log files (*.log) 로그 파일 (*.log) - + Save log 로그 저장 - - - + + + Cannot write file %1: %2. %1 파일을 쓸 수 없습니다: %2. - + Save Raw log... Raw 로그 저장... - + binary files (*.bin) 바이너리 파일 (*.bin) - + Save Raw log Raw 로그 저장 - + Unlock Session 세션 잠금 해제 - + Wrong password! 잘못된 비밀번호! - + Receive ASCII File ASCII 파일 받기 @@ -4662,6 +4606,34 @@ PowerShell 5 이상을 사용하십시오! 전송 정보 + + TerminalDisplay + + + Size: XXX x XXX + 크기: XXX x XXX + + + + Size: %1 x %2 + 크기: %1 x %2 + + + + Paste multiline text + 여러 줄 텍스트 붙여넣기 + + + + Are you sure you want to paste this text? + 이 텍스트를 붙여넣으시겠습니까? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Ctrl+S를 눌러 출력이 <a href="http://en.wikipedia.org/wiki/Flow_control">중지</a>되었습니다. 재개하려면 <b>Ctrl+Q</b>를 누르십시오.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ PowerShell 5 이상을 사용하십시오! %1 문자 덮어쓰기 + + UrlFilter + + + Follow link (ctrl + click) + 링크 따라가기 (ctrl + 클릭) + + + + Follow path (ctrl + click) + 경로 따라가기 (ctrl + 클릭) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 사용 가능한 키보드 변환기가 없습니다. 키를 문자로 변환하여 터미널로 보내는 데 필요한 정보가 없습니다. + + keyMapManager diff --git a/lang/quardCRT_pt_BR.ts b/lang/quardCRT_pt_BR.ts index df7f5b33..24500b85 100644 --- a/lang/quardCRT_pt_BR.ts +++ b/lang/quardCRT_pt_BR.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Barra de ferramentas @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Aviso @@ -285,7 +285,7 @@ - + Ready Pronto @@ -464,7 +464,7 @@ - + Help Ajuda @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Informe o host <Alt+R> para conectar - + Disconnect All Desconectar todas - + Disconnect all sessions Desconectar todas as sessões - + Clone Session Clonar sessão - + Clone current session <Ctrl+Shift+T> Clonar sessão atual <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Bloquear sessão - + Log Session Log da sessão - + Create a log file for current session Criar um arquivo de log para a sessão atual - + Raw Log Session Log bruto da sessão - + Create a raw log file for current session Criar um arquivo de log bruto para a sessão atual - + Hex View Visualização hexadecimal - + Show/Hide Hex View for current session Mostrar/Ocultar visualização hexadecimal para a sessão atual - + Exit Sair - + Quit the application Fechar o aplicativo - + Copy Copiar - + Copy the selected text to the clipboard <Command+C> Copiar o texto selecionado para a área de transferência <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Copiar o texto selecionado para a área de transferência <Ctrl+Ins> - + Paste Colar - + Paste the clipboard text to the current session <Command+V> Colar o texto da área de transferência na sessão atual <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Colar o texto da área de transferência na sessão atual <Shift+Ins> - + Copy and Paste Copiar e colar - + Copy the selected text to the clipboard and paste to the current session Copiar o texto selecionado para a área de transferência e colar na sessão atual - + Select All Selecionar tudo - + Select all text in the current session <Ctrl+Shift+A> Selecionar todo o texto na sessão atual <Ctrl+Shift+A> - + Find... Localizar... - + Find text in the current session <Ctrl+F> Localizar texto na sessão atual <Ctrl+F> - + Print Screen Imprimir tela - + Print current screen Imprimir tela atual - + Screen Shot Captura de tela - + Screen shot current screen <Alt+P> Captura de tela da tela atual <Alt+P> - + Session Export Exportar sessão - + Export current session to a file <Alt+O> Exportar sessão atual para um arquivo <Alt+O> - + Clear Scrollback Limpar rolagem - + Clear the contents of the scrollback rows Limpar o conteúdo das linhas de rolagem - + Clear Screen Limpar tela - + Clear the contents of the current screen Limpar o conteúdo da tela atual - + Clear Screen and Scrollback Limpar tela e rolagem - + Clear the contents of the screen and scrollback Limpar o conteúdo da tela e rolagem - + Reset Redefinir - + Reset terminal emulator Redefinir emulador de terminal - + Zoom In Ampliar - + Zoom In <Ctrl+"="> Ampliar <Ctrl+"="> - + Zoom Out Reduzir - + Zoom Out <Ctrl+"-"> Reduzir <Ctrl+"-"> - - + + Zoom Reset Redefinir zoom - + Layout Layout - + Single Layout Layout único - + Single layout Layout único - + Two Columns Layout Layout de duas colunas - + Two columns layout Layout de duas colunas - + Three Columns Layout Layout de três colunas - + Three columns layout Layout de três colunas - + Two Rows Layout Layout de duas linhas - + Two rows layout Layout de duas linhas - + Three Rows Layout Layout de três linhas - + Three rows layout Layout de três linhas - + Grid Layout Layout de grade - + Grid layout Layout de grade - + Two Rows Right Layout Layout de duas linhas à direita - + Two rows right layout Layout de duas linhas à direita - + Two Columns Bottom Layout Layout de duas colunas na parte inferior - + Two columns bottom layout Layout de duas colunas na parte inferior - + Flip Layout Virar layout - + Flip layout Virar layout - + Menu Bar Barra de menu - + Show/Hide Menu Bar <Alt+U> Mostrar/Ocultar barra de menu <Alt+U> - + Show/Hide Tool Bar Mostrar/Ocultar barra de ferramentas - + Status Bar Barra de status - + Show/Hide Status Bar Mostrar/Ocultar barra de status - + Command Window Janela de comando - + Show/Hide Command Window Mostrar/Ocultar janela de comando - + Connect Bar Barra de conexão - + Show/Hide Connect Bar Mostrar/Ocultar barra de conexão - + Side Window Janela lateral - + Show/Hide Side Window Mostrar/Ocultar janela lateral - + Windows Transparency Transparência das janelas - + Enable/Disable alpha transparency Ativar/Desativar transparência alfa - + Vertical Scroll Bar Barra de rolagem vertical - + Show/Hide Vertical Scroll Bar Mostrar/Ocultar barra de rolagem vertical - + Allways On Top Sempre no topo - + Show window always on top Mostrar janela sempre no topo - + Full Screen Tela cheia - + Toggle between full screen and normal mode <Alt+Enter> Alternar entre tela cheia e modo normal <Alt+Enter> - + Session Options... Opções da sessão... - + Configure session options Configurar opções da sessão - + Global Options... Opções globais... - + Configure global options Configurar opções globais - + Real-time Save Options Salvar opções em tempo real - + Real-time save session options and global options Salvar opções da sessão e opções globais em tempo real - + Save Settings Now Salvar configurações agora - + Save options configuration now Salvar configuração de opções agora - + Send ASCII... Enviar ASCII... - + Send ASCII file Enviar arquivo ASCII - + Receive ASCII... Receber ASCII... - + Receive ASCII file Receber arquivo ASCII - + Send Binary... Enviar binário... - + Send Binary file Enviar arquivo binário - + Send Kermit... Enviar Kermit... - + Send a file using Kermit Enviar um arquivo usando Kermit - + Receive Kermit... Receber Kermit... - + Receive a file using Kermit Receber um arquivo usando Kermit - + Send Xmodem... Enviar Xmodem... - + Send a file using Xmodem Enviar um arquivo usando Xmodem - + Receive Xmodem... Receber Xmodem... - + Receive a file using Xmodem Receber um arquivo usando Xmodem - + Send Ymodem... Enviar Ymodem... - + Send a file using Ymodem Enviar um arquivo usando Ymodem - + Receive Ymodem... Receber Ymodem... - + Receive a file using Ymodem Receber um arquivo usando Ymodem - + Zmodem Upload List... Lista de envio Zmodem... - + Display Zmodem file upload list Mostrar lista de envio de arquivos Zmodem - + Start Zmodem Upload Iniciar envio Zmodem - + Start Zmodem file upload Iniciar envio de arquivo Zmodem - + Start TFTP Server Iniciar servidor TFTP - + Start/Stop the TFTP server Iniciar/Parar o servidor TFTP - + Run... Executar... - + Run a script Executar um script - + Cancel Cancelar @@ -1213,759 +1214,759 @@ Alterar cor - + Cancel script execution Cancelar execução de script - + Start Recording Script Iniciar gravação de script - + Start recording script Iniciar gravação de script - + Stop Recording Script... Parar gravação de script... - + Stop recording script Parar gravação de script - + Cancel Recording Script Cancelar gravação de script - + Cancel recording script Cancelar gravação de script - + Add Bookmark Adicionar favorito - + Add a bookmark Adicionar um favorito - - + + Remove Bookmark Remover favorito - + Remove a bookmark Remover um favorito - - + + Clean All Bookmark Limpar todos os favoritos - + Clean all bookmark Limpar todos os favoritos - + Keymap Manager Gerenciador de mapeamento de teclas - + Display keymap editor Mostrar editor de mapeamento de teclas - + Create Public Key... Criar chave pública... - + Create a public key Criar uma chave pública - + Publickey Manager Gerenciador de chaves públicas - + Display publickey manager Mostrar gerenciador de chaves públicas - + Internal Command Comando interno - + Display Internal Command window Mostrar janela de comando interno - + Tab Aba - + Arrange sessions in tabs Organizar sessões em abas - + Tile Mosaico - + Arrange sessions in non-overlapping tiles Organizar sessões em mosaicos não sobrepostos - + Cascade Cascata - + Arrange sessions to overlap each other Organizar sessões para se sobrepor umas às outras - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Light Claro - + Switch to light theme Mudar para o tema claro - + Dark Escuro - + Switch to dark theme Mudar para o tema escuro - + Theme Color Cor do tema - + Set theme color, cancel to use default Definir cor do tema, cancelar para usar o padrão - + Display help Mostrar ajuda - - + + Keyborad Shortcuts Reference Referência de atalhos do teclado - + Display keyborad shortcuts reference Mostrar referência de atalhos do teclado - + Check Update Verificar atualização - + Check for updates Verificar atualizações - - + + Privacy Statement Declaração de privacidade - + Display privacy statement Mostrar declaração de privacidade - - + + About Sobre - + Display about dialog Mostrar diálogo sobre - + About Qt Sobre o Qt - + Display about Qt dialog Mostrar diálogo sobre o Qt - - + + About Python Sobre o Python - + Display about Python dialog Mostrar diálogo sobre o Python - + Laboratory Laboratório - - + + SSH Scanning Varredura SSH - + Display SSH scanning dialog Mostrar diálogo de varredura SSH - + Plugin Info Informações do plugin - + Display plugin information dialog Mostrar diálogo de informações do plugin - + Plugin metaData not found! Metadados do plugin não encontrados! - + Plugin api version not found! Versão da API do plugin não encontrada! - + Plugin api version not match! Versão da API do plugin não corresponde! - + Plugin menu not found! Menu do plugin não encontrado! - + Plugin init failed! Falha na inicialização do plugin! - + PrintScreen saved to %1 PrintScreen salvo em %1 - + Save Screenshot Salvar captura de tela - + Image Files (*.jpg) Arquivos de imagem (*.jpg) - - + + Screenshot saved to %1 Captura de tela salva em %1 - + Save Session Export Salvar exportação de sessão - + Text Files (*.txt);;HTML Files (*.html) Arquivos de texto (*.txt);;Arquivos HTML (*.html) - + Text Files (*.txt) Arquivos de texto (*.txt) - + HTML Files (*.html) Arquivos HTML (*.html) - + Session Export saved to %1 Exportação de sessão salva em %1 - + Session Export failed to save to %1 Falha ao salvar a exportação de sessão em %1 - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! A sessão de transmissão não pode transferir arquivos! - + Select Files to Send as ASCII Selecionar arquivos para enviar como ASCII - - + + Text Files (*.txt);;All Files (*) Arquivos de texto (*.txt);;Todos os arquivos (*) - + Save Received Data as ASCII Salvar dados recebidos como ASCII - + Select Files to Send as BINARY Selecionar arquivos para enviar como BINÁRIO - - - - - - + + + + + + All Files (*) Todos os arquivos (*) - + Select Files to Send using Kermit Selecionar arquivos para enviar usando Kermit - + Select Files to Send using Xmodem Selecionar arquivos para enviar usando Xmodem - + Save Received Files using Xmodem Salvar arquivos recebidos usando Xmodem - + Select Files to Send using Ymodem Selecionar arquivos para enviar usando Ymodem - + Select Files to Send using Zmodem Selecionar arquivos para enviar usando Zmodem - + Select a script file Selecione um arquivo de script - + Python Files (*.py);;All Files (*) Arquivos Python (*.py);;Todos os arquivos (*) - + Select a directory Selecione um diretório - + Select a bookmark Selecione um favorito - + Are you sure to clean all bookmark? Você tem certeza de que deseja limpar todos os favoritos? - + Port Porta - + Select color Selecionar cor - + Video background is enabled, please enable animation in global options (more system resources) or change background image. O plano de fundo de vídeo está ativado, ative a animação nas opções globais (mais recursos do sistema) ou altere a imagem de fundo. - + Session information get failed. Falha ao obter informações da sessão. - + Telnet - Telnet - - + Telnet Telnet - + Serial - Serial - - + Serial Serial - + Raw - Raw - - + Raw Raw - + NamePipe - NamePipe - - + NamePipe NamePipe - - + + Local Shell Shell local - + Local Shell - Shell local - - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Este software é um emulador de terminal que fornece uma conexão shell segura (SSH), conexão telnet, conexão de porta serial e outras funções. - + This software does not collect any personal information, and does not send any information to the server. Este software não coleta nenhuma informação pessoal e não envia nenhuma informação para o servidor. - + This software does not contain any malicious code, and does not contain any backdoors. Este software não contém nenhum código malicioso e não contém nenhuma porta dos fundos. - + This software is open source software, you can view the source code on the github website. Este software é um software de código aberto, você pode visualizar o código-fonte no site do github. - + This software is provided as is, without any warranty. Este software é fornecido como está, sem qualquer garantia. - + If you have any questions or suggestions, please contact the author. Se você tiver alguma dúvida ou sugestão, entre em contato com o autor. - + Version Versão - + Commit Commit - + Date Data - - + + Author Autor - + Are you sure to disconnect " Você tem certeza de que deseja desconectar " - + " session? " sessão? - + Website Site - + Global Shortcuts: Atalhos globais: - + show/hide menu bar mostrar/ocultar barra de menu - + connect to LocalShell conectar ao Shell local - + clone current session clonar sessão atual - + switch ui to STD mode alternar interface do usuário para o modo STD - + switch ui to MINI mode alternar interface do usuário para o modo MINI - + switch to previous session alternar para a sessão anterior - + switch to next session alternar para a próxima sessão - + switch to session [num] alternar para a sessão [num] - + Go to line start Ir para o início da linha - + Go to line end Ir para o final da linha - + There are sessions that have not yet been unlocked, please unlock them first. Há sessões que ainda não foram desbloqueadas, desbloqueie-as primeiro. - + Are you sure to quit? Você tem certeza de que deseja sair? @@ -2707,8 +2708,8 @@ - - + + Warning Aviso @@ -2745,7 +2746,7 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi - + The Default Local Shell is not a valid file! O Shell local padrão não é um arquivo válido! @@ -2795,7 +2796,7 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi Transferir - + The User Plugins Path is not a directory! O caminho dos plugins do usuário não é um diretório! @@ -2869,93 +2870,36 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi Comando interno - + Copy Copiar - + Paste Colar - + Select All Selecionar tudo - + Find Localizar - + Zoom In Ampliar - + Zoom Out Reduzir - - Session - - - Bell in session '%1' - Sinal sonoro na sessão '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Tamanho: XXX x XXX - - - - Size: %1 x %2 - Tamanho: %1 x %2 - - - - Paste multiline text - Colar texto multilinha - - - - Are you sure you want to paste this text? - Você tem certeza de que deseja colar este texto? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspensa</a> pressionando Ctrl+S. Pressione <b>Ctrl+Q</b> para retomar.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Seguir link (ctrl + clique) - - - - Follow path (ctrl + click) - Seguir caminho (ctrl + clique) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - Nenhum tradutor de teclado disponível. As informações necessárias para converter as teclas pressionadas em caracteres a serem enviados ao terminal estão faltando. - - LockSessionWindow @@ -3484,47 +3428,47 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi QObject - + Un-named Color Scheme Esquema de cores sem nome - + Accessible Color Scheme Esquema de cores acessível - + Open Link Abrir link - + Copy Link Address Copiar endereço do link - + Send Email To... Enviar e-mail para... - + Copy Email Address Copiar endereço de e-mail - + Open Path Abrir caminho - + Open Containing Folder Abrir pasta contendo - + Copy Path Copiar caminho @@ -3587,12 +3531,12 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi QTermWidget - + Color Scheme Error Erro no esquema de cores - + Cannot load color scheme: %1 Não é possível carregar o esquema de cores: %1 @@ -3897,20 +3841,20 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi Localizar: - - + + Match case Coincidir maiúsculas e minúsculas - - + + Regular expression Expressão regular - - + + Highlight all matches Realçar todas as correspondências @@ -4252,25 +4196,25 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi SessionsWindow - + Telnet Error Erro no Telnet - + Telnet error: %1. Erro no Telnet: %1. - - + + Serial Error Erro serial - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi %1. - + Raw Socket Error Erro no soquete bruto - + Raw Socket error: %1. Erro no soquete bruto: %1. - + Name Pipe Error Erro no tubo nomeado - + Name Pipe error: %1. Erro no tubo nomeado: %1. - - + + SSH2 Error Erro SSH2 - - + + SSH2 error: %1. Erro SSH2: %1. - - + + Open URL Abrir URL - - + + Cannot open URL %1. Não é possível abrir a URL %1. - + Select Files to Send using Zmodem Selecionar arquivos para enviar usando Zmodem - + All Files (*) Todos os arquivos (*) - + Start Local Shell Iniciar shell local - + Cannot start local shell: %1. Não é possível iniciar o shell local: %1. - + Serial port %1 has been removed. A porta serial %1 foi removida. - + Save log... Salvar log... - + log files (*.log) arquivos de log (*.log) - + Save log Salvar log - - - + + + Cannot write file %1: %2. Não é possível escrever o arquivo %1: %2. - + Save Raw log... Salvar log bruto... - + binary files (*.bin) arquivos binários (*.bin) - + Save Raw log Salvar log bruto - + Unlock Session Desbloquear sessão - + Wrong password! Senha incorreta! - + Receive ASCII File Receber arquivo ASCII @@ -4662,6 +4606,34 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi Informações de transferência + + TerminalDisplay + + + Size: XXX x XXX + Tamanho: XXX x XXX + + + + Size: %1 x %2 + Tamanho: %1 x %2 + + + + Paste multiline text + Colar texto multilinha + + + + Are you sure you want to paste this text? + Você tem certeza de que deseja colar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspensa</a> pressionando Ctrl+S. Pressione <b>Ctrl+Q</b> para retomar.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ Se você precisar usar outro shell, crie uma sessão através de [conexão rápi Sobrescrever %1 caracteres + + UrlFilter + + + Follow link (ctrl + click) + Seguir link (ctrl + clique) + + + + Follow path (ctrl + click) + Seguir caminho (ctrl + clique) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nenhum tradutor de teclado disponível. As informações necessárias para converter as teclas pressionadas em caracteres a serem enviados ao terminal estão faltando. + + keyMapManager diff --git a/lang/quardCRT_ru_RU.ts b/lang/quardCRT_ru_RU.ts index f2311b2d..44371c9a 100644 --- a/lang/quardCRT_ru_RU.ts +++ b/lang/quardCRT_ru_RU.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar Панель инструментов @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning Предупреждение @@ -285,7 +285,7 @@ - + Ready Готово @@ -464,7 +464,7 @@ - + Help Помощь @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect Введите хост <Alt+R> для подключения - + Disconnect All Отключить все - + Disconnect all sessions Отключить все сессии - + Clone Session Клонировать сессию - + Clone current session <Ctrl+Shift+T> Клонировать текущую сессию <Ctrl+Shift+T> @@ -595,564 +596,564 @@ Блокировка сессии - + Log Session Журнал сессии - + Create a log file for current session Создать файл журнала для текущей сессии - + Raw Log Session Сырой журнал сессии - + Create a raw log file for current session Создать сырой файл журнала для текущей сессии - + Hex View Шестнадцатеричный просмотр - + Show/Hide Hex View for current session Показать/Скрыть шестнадцатеричный просмотр для текущей сессии - + Exit Выход - + Quit the application Выйти из приложения - + Copy Копировать - + Copy the selected text to the clipboard <Command+C> Копировать выделенный текст в буфер обмена <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> Копировать выделенный текст в буфер обмена <Ctrl+Ins> - + Paste Вставить - + Paste the clipboard text to the current session <Command+V> Вставить текст из буфера обмена в текущую сессию <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> Вставить текст из буфера обмена в текущую сессию <Shift+Ins> - + Copy and Paste Копировать и вставить - + Copy the selected text to the clipboard and paste to the current session Копировать выделенный текст в буфер обмена и вставить в текущую сессию - + Select All Выделить все - + Select all text in the current session <Ctrl+Shift+A> Выделить весь текст в текущей сессии <Ctrl+Shift+A> - + Find... Найти... - + Find text in the current session <Ctrl+F> Найти текст в текущей сессии <Ctrl+F> - + Print Screen Печать экрана - + Print current screen Печать текущего экрана - + Screen Shot Снимок экрана - + Screen shot current screen <Alt+P> Снимок текущего экрана <Alt+P> - + Session Export Экспорт сессии - + Export current session to a file <Alt+O> Экспортировать текущую сессию в файл <Alt+O> - + Clear Scrollback Очистить буфер прокрутки - + Clear the contents of the scrollback rows Очистить содержимое строк буфера прокрутки - + Clear Screen Очистить экран - + Clear the contents of the current screen Очистить содержимое текущего экрана - + Clear Screen and Scrollback Очистить экран и буфер прокрутки - + Clear the contents of the screen and scrollback Очистить содержимое экрана и буфера прокрутки - + Reset Сбросить - + Reset terminal emulator Сбросить эмулятор терминала - + Zoom In Увеличить - + Zoom In <Ctrl+"="> Увеличить <Ctrl+"="> - + Zoom Out Уменьшить - + Zoom Out <Ctrl+"-"> Уменьшить <Ctrl+"-"> - - + + Zoom Reset Сбросить масштаб - + Layout Макет - + Single Layout Одиночный макет - + Single layout Одиночный макет - + Two Columns Layout Двухколоночный макет - + Two columns layout Двухколоночный макет - + Three Columns Layout Трехколоночный макет - + Three columns layout Трехколоночный макет - + Two Rows Layout Двухстрочный макет - + Two rows layout Двухстрочный макет - + Three Rows Layout Трехстрочный макет - + Three rows layout Трехстрочный макет - + Grid Layout Сеточный макет - + Grid layout Сеточный макет - + Two Rows Right Layout Две строки справа - + Two rows right layout Две строки справа - + Two Columns Bottom Layout Две колонки снизу - + Two columns bottom layout Две колонки снизу - + Flip Layout Перевернуть макет - + Flip layout Перевернуть макет - + Menu Bar Меню - + Show/Hide Menu Bar <Alt+U> Показать/Скрыть меню <Alt+U> - + Show/Hide Tool Bar Показать/Скрыть панель инструментов - + Status Bar Строка состояния - + Show/Hide Status Bar Показать/Скрыть строку состояния - + Command Window Окно команд - + Show/Hide Command Window Показать/Скрыть окно команд - + Connect Bar Панель подключения - + Show/Hide Connect Bar Показать/Скрыть панель подключения - + Side Window Боковое окно - + Show/Hide Side Window Показать/Скрыть боковое окно - + Windows Transparency Прозрачность окон - + Enable/Disable alpha transparency Включить/Выключить альфа прозрачность - + Vertical Scroll Bar Вертикальная полоса прокрутки - + Show/Hide Vertical Scroll Bar Показать/Скрыть вертикальную полосу прокрутки - + Allways On Top Поверх всех окон - + Show window always on top Показать окно поверх всех окон - + Full Screen Полный экран - + Toggle between full screen and normal mode <Alt+Enter> Переключиться между полноэкранным и нормальным режимом <Alt+Enter> - + Session Options... Настройки сессии... - + Configure session options Настроить параметры сессии - + Global Options... Глобальные настройки... - + Configure global options Настроить глобальные параметры - + Real-time Save Options Настройки сохранения в реальном времени - + Real-time save session options and global options Настройки сохранения сессии и глобальные настройки в реальном времени - + Save Settings Now Сохранить настройки сейчас - + Save options configuration now Сохранить конфигурацию настроек сейчас - + Send ASCII... Отправить ASCII... - + Send ASCII file Отправить файл ASCII - + Receive ASCII... Принять ASCII... - + Receive ASCII file Принять файл ASCII - + Send Binary... Отправить бинарный файл... - + Send Binary file Отправить бинарный файл - + Send Kermit... Отправить Kermit... - + Send a file using Kermit Отправить файл, используя Kermit - + Receive Kermit... Принять Kermit... - + Receive a file using Kermit Принять файл, используя Kermit - + Send Xmodem... Отправить Xmodem... - + Send a file using Xmodem Отправить файл, используя Xmodem - + Receive Xmodem... Принять Xmodem... - + Receive a file using Xmodem Принять файл, используя Xmodem - + Send Ymodem... Отправить Ymodem... - + Send a file using Ymodem Отправить файл, используя Ymodem - + Receive Ymodem... Принять Ymodem... - + Receive a file using Ymodem Принять файл, используя Ymodem - + Zmodem Upload List... Список загрузки Zmodem... - + Display Zmodem file upload list Показать список загрузки файлов Zmodem - + Start Zmodem Upload Начать загрузку Zmodem - + Start Zmodem file upload Начать загрузку файла Zmodem - + Start TFTP Server Запустить TFTP сервер - + Start/Stop the TFTP server Запустить/Остановить TFTP сервер - + Run... Запустить... - + Run a script Запустить скрипт - + Cancel Отменить @@ -1213,759 +1214,759 @@ Изменить цвет - + Cancel script execution Отменить выполнение скрипта - + Start Recording Script Начать запись скрипта - + Start recording script Начать запись скрипта - + Stop Recording Script... Остановить запись скрипта... - + Stop recording script Остановить запись скрипта - + Cancel Recording Script Отменить запись скрипта - + Cancel recording script Отменить запись скрипта - + Add Bookmark Добавить закладку - + Add a bookmark Добавить закладку - - + + Remove Bookmark Удалить закладку - + Remove a bookmark Удалить закладку - - + + Clean All Bookmark Очистить все закладки - + Clean all bookmark Очистить все закладки - + Keymap Manager Менеджер клавиатурных схем - + Display keymap editor Показать редактор клавиатурных схем - + Create Public Key... Создать публичный ключ... - + Create a public key Создать публичный ключ - + Publickey Manager Менеджер публичных ключей - + Display publickey manager Показать менеджер публичных ключей - + Internal Command Внутренняя команда - + Display Internal Command window Показать окно внутренних команд - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color Цвет темы - + Set theme color, cancel to use default Установить цвет темы, отменить для использования по умолчанию - - + + Keyborad Shortcuts Reference Справочник по клавиатурным сокращениям - + Display keyborad shortcuts reference Показать справочник по клавиатурным сокращениям - - + + Privacy Statement Заявление о конфиденциальности - + Display privacy statement Показать заявление о конфиденциальности - - + + About Python О Python - + Display about Python dialog Показать диалоговое окно о Python - + Laboratory Лаборатория - - + + SSH Scanning Сканирование SSH - + Display SSH scanning dialog Показать диалог сканирования SSH - + Plugin metaData not found! Метаданные плагина не найдены! - + Plugin api version not found! Версия API плагина не найдена! - + Plugin api version not match! Версия API плагина не соответствует! - + Plugin menu not found! Меню плагина не найдено! - + Plugin init failed! Ошибка инициализации плагина! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! Сеанс широковещания не может передавать файлы! - + Select Files to Send as ASCII Выберите файлы для отправки в виде ASCII - - + + Text Files (*.txt);;All Files (*) Текстовые файлы (*.txt);;Все файлы (*) - + Save Received Data as ASCII Сохранить полученные данные в виде ASCII - + Select Files to Send as BINARY Выберите файлы для отправки в виде BINARY - - - - - - + + + + + + All Files (*) Все файлы (*) - + Select Files to Send using Kermit Выберите файлы для отправки с использованием Kermit - + Select Files to Send using Xmodem Выберите файлы для отправки с использованием Xmodem - + Save Received Files using Xmodem Сохранить полученные файлы с использованием Xmodem - + Select Files to Send using Ymodem Выберите файлы для отправки с использованием Ymodem - + Select Files to Send using Zmodem Выберите файлы для отправки с использованием Zmodem - + Select a script file Выберите файл скрипта - + Python Files (*.py);;All Files (*) Файлы Python (*.py);;Все файлы (*) - + Select color Выберите цвет - + Are you sure to disconnect " Вы уверены, что хотите отключиться от " - + " session? " сессии? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. Это эмулятор терминала, который обеспечивает безопасное соединение по протоколу SSH, соединение по протоколу telnet, соединение с последовательным портом и другие функции. - + This software does not collect any personal information, and does not send any information to the server. Это программное обеспечение не собирает никакой личной информации и не отправляет никакую информацию на сервер. - + This software does not contain any malicious code, and does not contain any backdoors. Это программное обеспечение не содержит вредоносного кода и не содержит никаких задних дверей. - + This software is open source software, you can view the source code on the github website. Это программное обеспечение с открытым исходным кодом, вы можете просмотреть исходный код на веб-сайте github. - + This software is provided as is, without any warranty. Это программное обеспечение предоставляется "как есть", без каких-либо гарантий. - + If you have any questions or suggestions, please contact the author. Если у вас есть какие-либо вопросы или предложения, пожалуйста, свяжитесь с автором. - + Version Версия - + Commit Коммит - + Date Дата - - + + Author Автор - + Website Вебсайт - + Tab Вкладка - + Arrange sessions in tabs Расположить сессии во вкладках - + Tile - + Arrange sessions in non-overlapping tiles Расположить сессии в неперекрывающихся плитках - + Cascade Каскад - + Arrange sessions to overlap each other Расположить сессии так, чтобы они перекрывали друг друга - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light Светлая - + Switch to light theme Переключиться на светлую тему - + Dark Темная - + Switch to dark theme Переключиться на темную тему - + Display help Показать справку - + Check Update Проверить обновления - + Check for updates Проверить наличие обновлений - - + + About О программе - + Display about dialog Показать диалоговое окно "О программе" - + About Qt О Qt - + Display about Qt dialog Показать диалоговое окно "О Qt" - + Plugin Info Информация о плагине - + Display plugin information dialog Показать диалоговое окно информации о плагине - + PrintScreen saved to %1 Снимок экрана сохранен в %1 - + Save Screenshot Сохранить снимок экрана - + Image Files (*.jpg) Файлы изображений (*.jpg) - - + + Screenshot saved to %1 Снимок экрана сохранен в %1 - + Save Session Export Сохранить экспорт сессии - + Text Files (*.txt);;HTML Files (*.html) Текстовые файлы (*.txt);;HTML файлы (*.html) - + Text Files (*.txt) Текстовые файлы (*.txt) - + HTML Files (*.html) HTML файлы (*.html) - + Session Export saved to %1 Экспорт сессии сохранен в %1 - + Session Export failed to save to %1 Экспорт сессии не удалось сохранить в %1 - + Select a directory Выберите каталог - + Select a bookmark Выберите закладку - + Are you sure to clean all bookmark? Вы уверены, что хотите очистить все закладки? - + Port Порт - + Video background is enabled, please enable animation in global options (more system resources) or change background image. Включен видеофон, пожалуйста, включите анимацию в глобальных настройках (больше системных ресурсов) или измените фоновое изображение. - + Session information get failed. Не удалось получить информацию о сессии. - + Telnet - Телнет - - + Telnet Телнет - + Serial - Серийный порт - - + Serial Серийный порт - + Raw - Raw - - + Raw Raw - + NamePipe - Именованный канал - - + NamePipe Именованный канал - - + + Local Shell Локальная оболочка - + Local Shell - Локальная оболочка - - + Global Shortcuts: Глобальные ярлыки: - + show/hide menu bar показать/скрыть меню - + connect to LocalShell подключиться к локальной оболочке - + clone current session клонировать текущую сессию - + switch ui to STD mode переключить интерфейс в режим STD - + switch ui to MINI mode переключить интерфейс в режим MINI - + switch to previous session переключиться на предыдущую сессию - + switch to next session переключиться на следующую сессию - + switch to session [num] переключиться на сессию [num] - + Go to line start Перейти в начало строки - + Go to line end Перейти в конец строки - + There are sessions that have not yet been unlocked, please unlock them first. Есть сессии, которые еще не были разблокированы, пожалуйста, сначала разблокируйте их. - + Are you sure to quit? Вы уверены, что хотите выйти? @@ -2707,8 +2708,8 @@ - - + + Warning Предупреждение @@ -2745,7 +2746,7 @@ If you need to use another shell, please create a session through [quick-connect - + The Default Local Shell is not a valid file! Локальная оболочка по умолчанию не является допустимым файлом! @@ -2795,7 +2796,7 @@ If you need to use another shell, please create a session through [quick-connect Передача - + The User Plugins Path is not a directory! Путь к пользовательским плагинам не является каталогом! @@ -2869,93 +2870,36 @@ If you need to use another shell, please create a session through [quick-connect Внутренняя команда - + Copy Копировать - + Paste Вставить - + Select All Выделить все - + Find Найти - + Zoom In Увеличить - + Zoom Out Уменьшить - - Session - - - Bell in session '%1' - Сигнал в сессии '%1' - - - - TerminalDisplay - - - Size: XXX x XXX - Размер: XXX x XXX - - - - Size: %1 x %2 - Размер: %1 x %2 - - - - Paste multiline text - Вставить многострочный текст - - - - Are you sure you want to paste this text? - Вы уверены, что хотите вставить этот текст? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>Вывод был <a href="http://en.wikipedia.org/wiki/Flow_control">приостановлен</a> нажатием Ctrl+S. Нажмите <b>Ctrl+Q</b> для продолжения.</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - Перейти по ссылке (ctrl + click) - - - - Follow path (ctrl + click) - Перейти по пути (ctrl + click) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - Нет доступного переводчика клавиатуры. Недостающая информация для преобразования нажатий клавиш в символы для отправки в терминал. - - LockSessionWindow @@ -3484,47 +3428,47 @@ If you need to use another shell, please create a session through [quick-connect QObject - + Un-named Color Scheme Безымянная цветовая схема - + Accessible Color Scheme Доступная цветовая схема - + Open Link Открыть ссылку - + Copy Link Address Копировать адрес ссылки - + Send Email To... Отправить письмо на... - + Copy Email Address Копировать адрес электронной почты - + Open Path Открыть путь - + Open Containing Folder Открыть папку с содержимым - + Copy Path Копировать путь @@ -3587,12 +3531,12 @@ If you need to use another shell, please create a session through [quick-connect QTermWidget - + Color Scheme Error Ошибка цветовой схемы - + Cannot load color scheme: %1 Не удается загрузить цветовую схему: %1 @@ -3897,20 +3841,20 @@ If you need to use another shell, please create a session through [quick-connect Найти: - - + + Match case Учитывать регистр - - + + Regular expression Регулярное выражение - - + + Highlight all matches Подсвечивать все совпадения @@ -4252,25 +4196,25 @@ If you need to use another shell, please create a session through [quick-connect SessionsWindow - + Telnet Error Ошибка Telnet - + Telnet error: %1. Ошибка Telnet: %1. - - + + Serial Error Ошибка серийного порта - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ If you need to use another shell, please create a session through [quick-connect %1. - + Raw Socket Error Ошибка Raw Socket - + Raw Socket error: %1. Ошибка Raw Socket: %1. - + Name Pipe Error Ошибка именованного канала - + Name Pipe error: %1. Ошибка именованного канала: %1. - - + + SSH2 Error Ошибка SSH2 - - + + SSH2 error: %1. Ошибка SSH2: %1. - - + + Open URL Открыть URL - - + + Cannot open URL %1. Не удалось открыть URL %1. - + Select Files to Send using Zmodem Выберите файлы для отправки с использованием Zmodem - + All Files (*) Все файлы (*) - + Start Local Shell Запустить локальную оболочку - + Cannot start local shell: %1. Не удалось запустить локальную оболочку: %1. - + Serial port %1 has been removed. Серийный порт %1 был удален. - + Save log... Сохранить журнал... - + log files (*.log) файлы журналов (*.log) - + Save log Сохранить журнал - - - + + + Cannot write file %1: %2. Не удалось записать файл %1: %2. - + Save Raw log... Сохранить Raw журнал... - + binary files (*.bin) бинарные файлы (*.bin) - + Save Raw log Сохранить Raw журнал - + Unlock Session Разблокировать сессию - + Wrong password! Неверный пароль! - + Receive ASCII File Получить ASCII файл @@ -4662,6 +4606,34 @@ If you need to use another shell, please create a session through [quick-connect Информация о передаче + + TerminalDisplay + + + Size: XXX x XXX + Размер: XXX x XXX + + + + Size: %1 x %2 + Размер: %1 x %2 + + + + Paste multiline text + Вставить многострочный текст + + + + Are you sure you want to paste this text? + Вы уверены, что хотите вставить этот текст? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Вывод был <a href="http://en.wikipedia.org/wiki/Flow_control">приостановлен</a> нажатием Ctrl+S. Нажмите <b>Ctrl+Q</b> для продолжения.</qt> + + UndoStack @@ -4680,6 +4652,27 @@ If you need to use another shell, please create a session through [quick-connect Перезапись %1 символов + + UrlFilter + + + Follow link (ctrl + click) + Перейти по ссылке (ctrl + click) + + + + Follow path (ctrl + click) + Перейти по пути (ctrl + click) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Нет доступного переводчика клавиатуры. Недостающая информация для преобразования нажатий клавиш в символы для отправки в терминал. + + keyMapManager diff --git a/lang/quardCRT_zh_CN.ts b/lang/quardCRT_zh_CN.ts index 69f38ce6..8dfbf16b 100644 --- a/lang/quardCRT_zh_CN.ts +++ b/lang/quardCRT_zh_CN.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar 工具栏 @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning 警告 @@ -285,7 +285,7 @@ - + Ready 就绪 @@ -464,7 +464,7 @@ - + Help 帮助 @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect 输入主机地址 <Alt+R> 连接 - + Disconnect All 断开所有连接 - + Disconnect all sessions 断开所有会话连接 - + Clone Session 克隆会话 - + Clone current session <Ctrl+Shift+T> 克隆当前会话 <Ctrl+Shift+T> @@ -595,564 +596,564 @@ 锁定会话 - + Log Session 记录日志 - + Create a log file for current session 为当前会话创建日志文件 - + Raw Log Session 记录原始日志 - + Create a raw log file for current session 为当前会话创建原始日志文件 - + Hex View 十六进制视图 - + Show/Hide Hex View for current session 显示/隐藏当前会话的十六进制视图 - + Exit 退出 - + Quit the application 退出应用程序 - + Copy 复制 - + Copy the selected text to the clipboard <Command+C> 复制选中的文本到剪贴板 <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> 复制选中的文本到剪贴板 <Ctrl+Ins> - + Paste 粘贴 - + Paste the clipboard text to the current session <Command+V> 粘贴剪贴板文本到当前会话 <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> 粘贴剪贴板文本到当前会话 <Shift+Ins> - + Copy and Paste 复制并粘贴 - + Copy the selected text to the clipboard and paste to the current session 复制选中的文本到剪贴板并粘贴到当前会话 - + Select All 全选 - + Select all text in the current session <Ctrl+Shift+A> 选择当前会话中的所有文本 <Ctrl+Shift+A> - + Find... 查找... - + Find text in the current session <Ctrl+F> 在当前会话中查找文本 <Ctrl+F> - + Print Screen 打印屏幕 - + Print current screen 打印当前屏幕 - + Screen Shot 屏幕截图 - + Screen shot current screen <Alt+P> 截屏当前屏幕 <Alt+P> - + Session Export 会话导出 - + Export current session to a file <Alt+O> 导出当前会话到文件 <Alt+O> - + Clear Scrollback 清除滚动行 - + Clear the contents of the scrollback rows 清除滚动行的内容 - + Clear Screen 清除屏幕 - + Clear the contents of the current screen 清除当前屏幕的内容 - + Clear Screen and Scrollback 清除屏幕和滚动行 - + Clear the contents of the screen and scrollback 清除屏幕和滚动行的内容 - + Reset 重置 - + Reset terminal emulator 重置终端仿真器 - + Zoom In 放大 - + Zoom In <Ctrl+"="> 放大 <Ctrl+"="> - + Zoom Out 缩小 - + Zoom Out <Ctrl+"-"> 缩小 <Ctrl+"-"> - - + + Zoom Reset 重置缩放 - + Layout 布局 - + Single Layout 单列布局 - + Single layout 单列布局 - + Two Columns Layout 两列布局 - + Two columns layout 两列布局 - + Three Columns Layout 三列布局 - + Three columns layout 三列布局 - + Two Rows Layout 两行布局 - + Two rows layout 两行布局 - + Three Rows Layout 三行布局 - + Three rows layout 三行布局 - + Grid Layout 网格布局 - + Grid layout 网格布局 - + Two Rows Right Layout 两行右侧布局 - + Two rows right layout 两行右侧布局 - + Two Columns Bottom Layout 两列底部布局 - + Two columns bottom layout 两列底部布局 - + Flip Layout 翻转布局 - + Flip layout 翻转布局 - + Menu Bar 菜单栏 - + Show/Hide Menu Bar <Alt+U> 显示/隐藏菜单栏 <Alt+U> - + Show/Hide Tool Bar 显示/隐藏工具栏 - + Status Bar 状态栏 - + Show/Hide Status Bar 显示/隐藏状态栏 - + Command Window 命令窗口 - + Show/Hide Command Window 显示/隐藏命令窗口 - + Connect Bar 连接栏 - + Show/Hide Connect Bar 显示/隐藏连接栏 - + Side Window 侧边窗口 - + Show/Hide Side Window 显示/隐藏侧边窗口 - + Windows Transparency 窗口透明度 - + Enable/Disable alpha transparency 启用/禁用透明度 - + Vertical Scroll Bar 垂直滚动条 - + Show/Hide Vertical Scroll Bar 显示/隐藏垂直滚动条 - + Allways On Top 总在最前 - + Show window always on top 总在最前显示窗口 - + Full Screen 全屏 - + Toggle between full screen and normal mode <Alt+Enter> 在全屏和正常模式之间切换 <Alt+Enter> - + Session Options... 会话选项... - + Configure session options 配置会话选项 - + Global Options... 全局选项... - + Configure global options 配置全局选项 - + Real-time Save Options 实时保存选项 - + Real-time save session options and global options 实时保存会话选项和全局选项 - + Save Settings Now 立即保存设置 - + Save options configuration now 立即保存选项配置 - + Send ASCII... 发送 ASCII... - + Send ASCII file 发送 ASCII 文件 - + Receive ASCII... 接收 ASCII... - + Receive ASCII file 接收 ASCII 文件 - + Send Binary... 发送二进制... - + Send Binary file 发送二进制文件 - + Send Kermit... 发送 Kermit... - + Send a file using Kermit 使用 Kermit 发送文件 - + Receive Kermit... 接收 Kermit... - + Receive a file using Kermit 使用 Kermit 接收文件 - + Send Xmodem... 发送 Xmodem... - + Send a file using Xmodem 使用 Xmodem 发送文件 - + Receive Xmodem... 接收 Xmodem... - + Receive a file using Xmodem 使用 Xmodem 接收文件 - + Send Ymodem... 发送 Ymodem... - + Send a file using Ymodem 使用 Ymodem 发送文件 - + Receive Ymodem... 接收 Ymodem... - + Receive a file using Ymodem 使用 Ymodem 接收文件 - + Zmodem Upload List... Zmodem 上传列表... - + Display Zmodem file upload list 显示 Zmodem 文件上传列表 - + Start Zmodem Upload 开始 Zmodem 上传 - + Start Zmodem file upload 开始 Zmodem 文件上传 - + Start TFTP Server 启动 TFTP 服务器 - + Start/Stop the TFTP server 启动/停止 TFTP 服务器 - + Run... 运行... - + Run a script 运行脚本 - + Cancel 取消 @@ -1213,759 +1214,759 @@ 更改颜色 - + Cancel script execution 取消脚本执行 - + Start Recording Script 开始录制脚本 - + Start recording script 开始录制脚本 - + Stop Recording Script... 停止录制脚本... - + Stop recording script 停止录制脚本 - + Cancel Recording Script 取消录制脚本 - + Cancel recording script 取消录制脚本 - + Add Bookmark 添加书签 - + Add a bookmark 添加书签 - - + + Remove Bookmark 删除书签 - + Remove a bookmark 删除书签 - - + + Clean All Bookmark 清除所有书签 - + Clean all bookmark 清除所有书签 - + Keymap Manager 键盘映射管理器 - + Display keymap editor 显示键盘映射编辑器 - + Create Public Key... 创建公钥... - + Create a public key 创建公钥 - + Publickey Manager 公钥管理器 - + Display publickey manager 显示公钥管理器 - + Internal Command 内部命令 - + Display Internal Command window 显示内部命令窗口 - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color 主题颜色 - + Set theme color, cancel to use default 设置主题颜色,取消使用默认值 - - + + Keyborad Shortcuts Reference 键盘快捷键参考 - + Display keyborad shortcuts reference 显示键盘快捷键参考 - - + + Privacy Statement 隐私声明 - + Display privacy statement 显示隐私声明 - - + + About Python 关于 Python - + Display about Python dialog 显示关于 Python 对话框 - + Laboratory 实验室 - - + + SSH Scanning SSH 扫描 - + Display SSH scanning dialog 显示 SSH 扫描对话框 - + Plugin metaData not found! 未找到插件元数据! - + Plugin api version not found! 未找到插件 API 版本! - + Plugin api version not match! 插件 API 版本不匹配! - + Plugin menu not found! 未找到插件菜单! - + Plugin init failed! 插件初始化失败! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! 广播会话无法传输文件! - + Select Files to Send as ASCII 选择要发送的文件为 ASCII - - + + Text Files (*.txt);;All Files (*) 文本文件 (*.txt);;所有文件 (*) - + Save Received Data as ASCII 将接收的数据保存为 ASCII - + Select Files to Send as BINARY 选择要发送的文件为二进制 - - - - - - + + + + + + All Files (*) 所有文件 (*) - + Select Files to Send using Kermit 选择要使用 Kermit 发送的文件 - + Select Files to Send using Xmodem 选择要使用 Xmodem 发送的文件 - + Save Received Files using Xmodem 使用 Xmodem 保存接收的文件 - + Select Files to Send using Ymodem 选择要使用 Ymodem 发送的文件 - + Select Files to Send using Zmodem 选择要使用 Zmodem 发送的文件 - + Select a script file 选择一个脚本文件 - + Python Files (*.py);;All Files (*) Python 文件 (*.py);;所有文件 (*) - + Select color 选择颜色 - + Are you sure to disconnect " 您确定要断开连接 " - + " session? " 会话? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. 此软件是一个终端仿真器,提供安全外壳 (SSH) 连接、 Telnet 连接、串口连接和其他功能。 - + This software does not collect any personal information, and does not send any information to the server. 此软件不收集任何个人信息,也不向服务器发送任何信息。 - + This software does not contain any malicious code, and does not contain any backdoors. 此软件不包含任何恶意代码,也不包含任何后门。 - + This software is open source software, you can view the source code on the github website. 此软件是开源软件,您可以在 github 网站上查看源代码。 - + This software is provided as is, without any warranty. 此软件按原样提供,不提供任何保证。 - + If you have any questions or suggestions, please contact the author. 如果您有任何问题或建议,请联系作者。 - + Version 版本 - + Commit 提交 - + Date 日期 - - + + Author 作者 - + Website 网站 - + Tab 标签 - + Arrange sessions in tabs 在标签中排列会话 - + Tile 平铺 - + Arrange sessions in non-overlapping tiles 在不重叠的平铺中排列会话 - + Cascade 层叠 - + Arrange sessions to overlap each other 排列会话以彼此重叠 - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light 明亮 - + Switch to light theme 切换到明亮主题 - + Dark 暗黑 - + Switch to dark theme 切换到暗黑主题 - + Display help 显示帮助 - + Check Update 检查更新 - + Check for updates 检查更新 - - + + About 关于 - + Display about dialog 显示关于对话框 - + About Qt 关于 Qt - + Display about Qt dialog 显示关于 Qt 对话框 - + Plugin Info 插件信息 - + Display plugin information dialog 显示插件信息窗口 - + PrintScreen saved to %1 打印屏幕保存到 %1 - + Save Screenshot 保存屏幕截图 - + Image Files (*.jpg) 图像文件 (*.jpg) - - + + Screenshot saved to %1 屏幕截图保存到 %1 - + Save Session Export 保存会话导出 - + Text Files (*.txt);;HTML Files (*.html) 文本文件 (*.txt);;HTML 文件 (*.html) - + Text Files (*.txt) 文本文件 (*.txt) - + HTML Files (*.html) HTML 文件 (*.html) - + Session Export saved to %1 会话导出保存到 %1 - + Session Export failed to save to %1 会话导出保存到 %1 失败 - + Select a directory 选择一个目录 - + Select a bookmark 选择一个书签 - + Are you sure to clean all bookmark? 您确定要清除所有书签吗? - + Port 端口 - + Video background is enabled, please enable animation in global options (more system resources) or change background image. 视频背景已启用,请在全局选项中启用动画(更多系统资源)或更改背景图像。 - + Session information get failed. 会话信息获取失败。 - + Telnet - - + Telnet - + Serial - 串行通讯 - - + Serial 串行通讯 - + Raw - - + Raw - + NamePipe - 命名管道 - - + NamePipe 命名管道 - - + + Local Shell 本机终端 - + Local Shell - 本机终端 - - + Global Shortcuts: 全局快捷键: - + show/hide menu bar 显示/隐藏菜单栏 - + connect to LocalShell 连接到本机终端 - + clone current session 克隆当前会话 - + switch ui to STD mode 切换 UI 到标准模式 - + switch ui to MINI mode 切换 UI 到迷你模式 - + switch to previous session 切换到上一个会话 - + switch to next session 切换到下一个会话 - + switch to session [num] 切换到会话 [num] - + Go to line start 跳转到行首 - + Go to line end 跳转到行尾 - + There are sessions that have not yet been unlocked, please unlock them first. 有会话尚未解锁,请先解锁。 - + Are you sure to quit? 确定要退出吗? @@ -2697,8 +2698,8 @@ - - + + Warning 警告 @@ -2735,7 +2736,7 @@ If you need to use another shell, please create a session through [quick-connect - + The Default Local Shell is not a valid file! 默认本地终端不是有效文件! @@ -2785,7 +2786,7 @@ If you need to use another shell, please create a session through [quick-connect 传输 - + The User Plugins Path is not a directory! 用户插件路径不是一个目录! @@ -2869,93 +2870,36 @@ If you need to use another shell, please create a session through [quick-connect 内部命令 - + Copy 复制 - + Paste 粘贴 - + Select All 全选 - + Find 查找 - + Zoom In 放大 - + Zoom Out 缩小 - - Session - - - Bell in session '%1' - 会话 '%1' 中的铃声 - - - - TerminalDisplay - - - Size: XXX x XXX - 大小: XXX x XXX - - - - Size: %1 x %2 - 大小: %1 x %2 - - - - Paste multiline text - 粘贴多行文本 - - - - Are you sure you want to paste this text? - 您确定要粘贴此文本吗? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>按下 Ctrl+S 已 <a href="http://en.wikipedia.org/wiki/Flow_control">挂起</a> 输出。按 <b>Ctrl+Q</b> 恢复。</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - 跳转链接 (ctrl + 单击) - - - - Follow path (ctrl + click) - 跳转路径 (ctrl + 单击) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - 没有可用的键盘转换器。缺少将按键转换为要发送到终端的字符所需的信息。 - - LockSessionWindow @@ -3484,47 +3428,47 @@ If you need to use another shell, please create a session through [quick-connect QObject - + Un-named Color Scheme 未命名的颜色方案 - + Accessible Color Scheme 可访问的颜色方案 - + Open Link 打开链接 - + Copy Link Address 复制链接 - + Send Email To... 发送邮件到... - + Copy Email Address 复制邮件地址 - + Open Path 打开路径 - + Open Containing Folder 打开包含的文件夹 - + Copy Path 复制路径 @@ -3587,12 +3531,12 @@ If you need to use another shell, please create a session through [quick-connect QTermWidget - + Color Scheme Error 颜色方案错误 - + Cannot load color scheme: %1 无法加载颜色方案:%1 @@ -3897,20 +3841,20 @@ If you need to use another shell, please create a session through [quick-connect 查找: - - + + Match case 区分大小写 - - + + Regular expression 正则表达式 - - + + Highlight all matches 高亮显示所有匹配项 @@ -4252,25 +4196,25 @@ If you need to use another shell, please create a session through [quick-connect SessionsWindow - + Telnet Error TELNET 错误 - + Telnet error: %1. TELNET 错误: %1. - - + + Serial Error 串行通讯错误 - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ If you need to use another shell, please create a session through [quick-connect %1. - + Raw Socket Error 原始套接字错误 - + Raw Socket error: %1. 原始套接字错误: %1. - + Name Pipe Error 命名管道错误 - + Name Pipe error: %1. 命名管道错误: %1. - - + + SSH2 Error SSH2 错误 - - + + SSH2 error: %1. SSH2 错误: %1. - - + + Open URL 打开 URL - - + + Cannot open URL %1. 无法打开 URL %1. - + Select Files to Send using Zmodem 选择要使用 Zmodem 发送的文件 - + All Files (*) 所有文件 (*) - + Start Local Shell 启动本机终端 - + Cannot start local shell: %1. 无法启动本机终端: %1. - + Serial port %1 has been removed. 串行端口 %1 已被移除。 - + Save log... 保存日志... - + log files (*.log) 日志文件 (*.log) - + Save log 保存日志 - - - + + + Cannot write file %1: %2. 无法写入文件 %1: %2. - + Save Raw log... 保存原始日志... - + binary files (*.bin) 二进制文件 (*.bin) - + Save Raw log 保存原始日志 - + Unlock Session 解锁会话 - + Wrong password! 密码错误! - + Receive ASCII File 接收 ASCII 文件 @@ -4662,6 +4606,34 @@ If you need to use another shell, please create a session through [quick-connect 传输信息 + + TerminalDisplay + + + Size: XXX x XXX + 大小: XXX x XXX + + + + Size: %1 x %2 + 大小: %1 x %2 + + + + Paste multiline text + 粘贴多行文本 + + + + Are you sure you want to paste this text? + 您确定要粘贴此文本吗? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>按下 Ctrl+S 已 <a href="http://en.wikipedia.org/wiki/Flow_control">挂起</a> 输出。按 <b>Ctrl+Q</b> 恢复。</qt> + + UndoStack @@ -4680,6 +4652,27 @@ If you need to use another shell, please create a session through [quick-connect 覆盖 %1 字符 + + UrlFilter + + + Follow link (ctrl + click) + 跳转链接 (ctrl + 单击) + + + + Follow path (ctrl + click) + 跳转路径 (ctrl + 单击) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 没有可用的键盘转换器。缺少将按键转换为要发送到终端的字符所需的信息。 + + keyMapManager diff --git a/lang/quardCRT_zh_HK.ts b/lang/quardCRT_zh_HK.ts index 87e60137..2afc9d7b 100644 --- a/lang/quardCRT_zh_HK.ts +++ b/lang/quardCRT_zh_HK.ts @@ -13,7 +13,7 @@ CentralWidget - + Tool Bar 工具欄 @@ -26,21 +26,21 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Warning 警告 @@ -285,7 +285,7 @@ - + Ready 就緒 @@ -464,7 +464,7 @@ - + Help 幫助 @@ -566,26 +566,27 @@ + Enter host <Alt+R> to connect 輸入主機 <Alt+R> 連接 - + Disconnect All 斷開所有 - + Disconnect all sessions 斷開所有會話 - + Clone Session 克隆會話 - + Clone current session <Ctrl+Shift+T> 克隆當前會話 <Ctrl+Shift+T> @@ -595,564 +596,564 @@ 鎖定會話 - + Log Session 記錄日誌 - + Create a log file for current session 為當前會話創建日誌文件 - + Raw Log Session 記錄原始日誌 - + Create a raw log file for current session 為當前會話創建原始日誌文件 - + Hex View 十六進制視圖 - + Show/Hide Hex View for current session 顯示/隱藏當前會話的十六進制視圖 - + Exit 退出 - + Quit the application 退出應用程序 - + Copy 複製 - + Copy the selected text to the clipboard <Command+C> 將所選文本複製到剪貼板 <Command+C> - + Copy the selected text to the clipboard <Ctrl+Ins> 將所選文本複製到剪貼板 <Ctrl+Ins> - + Paste 粘貼 - + Paste the clipboard text to the current session <Command+V> 將剪貼板文本粘貼到當前會話 <Command+V> - + Paste the clipboard text to the current session <Shift+Ins> 將剪貼板文本粘貼到當前會話 <Shift+Ins> - + Copy and Paste 複製和粘貼 - + Copy the selected text to the clipboard and paste to the current session 將所選文本複製到剪貼板並粘貼到當前會話 - + Select All 全選 - + Select all text in the current session <Ctrl+Shift+A> 選擇當前會話中的所有文本 <Ctrl+Shift+A> - + Find... 查找... - + Find text in the current session <Ctrl+F> 在當前會話中查找文本 <Ctrl+F> - + Print Screen 打印屏幕 - + Print current screen 打印當前屏幕 - + Screen Shot 屏幕截圖 - + Screen shot current screen <Alt+P> 截圖當前屏幕 <Alt+P> - + Session Export 會話導出 - + Export current session to a file <Alt+O> 將當前會話導出到文件 <Alt+O> - + Clear Scrollback 清除滾動內容 - + Clear the contents of the scrollback rows 清除滾動行的內容 - + Clear Screen 清除屏幕 - + Clear the contents of the current screen 清除當前屏幕的內容 - + Clear Screen and Scrollback 清除屏幕和滾動內容 - + Clear the contents of the screen and scrollback 清除屏幕和滾動內容的內容 - + Reset 重置 - + Reset terminal emulator 重置終端仿真器 - + Zoom In 放大 - + Zoom In <Ctrl+"="> 放大 <Ctrl+"="> - + Zoom Out 縮小 - + Zoom Out <Ctrl+"-"> 縮小 <Ctrl+"-"> - - + + Zoom Reset 重置縮放 - + Layout 佈局 - + Single Layout 單個佈局 - + Single layout 單個佈局 - + Two Columns Layout 兩列佈局 - + Two columns layout 兩列佈局 - + Three Columns Layout 三列佈局 - + Three columns layout 三列佈局 - + Two Rows Layout 兩行佈局 - + Two rows layout 兩行佈局 - + Three Rows Layout 三行佈局 - + Three rows layout 三行佈局 - + Grid Layout 網格佈局 - + Grid layout 網格佈局 - + Two Rows Right Layout 兩行右側佈局 - + Two rows right layout 兩行右側佈局 - + Two Columns Bottom Layout 兩列底部佈局 - + Two columns bottom layout 兩列底部佈局 - + Flip Layout 翻轉佈局 - + Flip layout 翻轉佈局 - + Menu Bar 菜單欄 - + Show/Hide Menu Bar <Alt+U> 顯示/隱藏菜單欄 <Alt+U> - + Show/Hide Tool Bar 顯示/隱藏工具欄 - + Status Bar 狀態欄 - + Show/Hide Status Bar 顯示/隱藏狀態欄 - + Command Window 命令窗口 - + Show/Hide Command Window 顯示/隱藏命令窗口 - + Connect Bar 連接欄 - + Show/Hide Connect Bar 顯示/隱藏連接欄 - + Side Window 側邊窗口 - + Show/Hide Side Window 顯示/隱藏側邊窗口 - + Windows Transparency 窗口透明 - + Enable/Disable alpha transparency 啟用/禁用alpha透明度 - + Vertical Scroll Bar 垂直滾動條 - + Show/Hide Vertical Scroll Bar 顯示/隱藏垂直滾動條 - + Allways On Top 總在最前 - + Show window always on top 總是顯示窗口在最上面 - + Full Screen 全屏 - + Toggle between full screen and normal mode <Alt+Enter> 在全屏模式和正常模式之間切換 <Alt+Enter> - + Session Options... 會話選項... - + Configure session options 配置會話選項 - + Global Options... 全局選項... - + Configure global options 配置全局選項 - + Real-time Save Options 實時保存選項 - + Real-time save session options and global options 實時保存會話選項和全局選項 - + Save Settings Now 立即保存設置 - + Save options configuration now 立即保存選項配置 - + Send ASCII... 發送ASCII... - + Send ASCII file 發送ASCII文件 - + Receive ASCII... 接收ASCII... - + Receive ASCII file 接收ASCII文件 - + Send Binary... 發送二進制... - + Send Binary file 發送二進制文件 - + Send Kermit... 發送Kermit... - + Send a file using Kermit 使用Kermit發送文件 - + Receive Kermit... 接收Kermit... - + Receive a file using Kermit 使用Kermit接收文件 - + Send Xmodem... 發送Xmodem... - + Send a file using Xmodem 使用Xmodem發送文件 - + Receive Xmodem... 接收Xmodem... - + Receive a file using Xmodem 使用Xmodem接收文件 - + Send Ymodem... 發送Ymodem... - + Send a file using Ymodem 使用Ymodem發送文件 - + Receive Ymodem... 接收Ymodem... - + Receive a file using Ymodem 使用Ymodem接收文件 - + Zmodem Upload List... Zmodem上傳列表... - + Display Zmodem file upload list 顯示Zmodem文件上傳列表 - + Start Zmodem Upload 開始Zmodem上傳 - + Start Zmodem file upload 開始Zmodem文件上傳 - + Start TFTP Server 啟動TFTP服務器 - + Start/Stop the TFTP server 啟動/停止TFTP服務器 - + Run... 運行... - + Run a script 運行腳本 - + Cancel 取消 @@ -1213,759 +1214,759 @@ 更改顏色 - + Cancel script execution 取消腳本執行 - + Start Recording Script 開始記錄腳本 - + Start recording script 開始記錄腳本 - + Stop Recording Script... 停止記錄腳本... - + Stop recording script 停止記錄腳本 - + Cancel Recording Script 取消記錄腳本 - + Cancel recording script 取消記錄腳本 - + Add Bookmark 添加書籤 - + Add a bookmark 添加書籤 - - + + Remove Bookmark 刪除書籤 - + Remove a bookmark 刪除書籤 - - + + Clean All Bookmark 清除所有書籤 - + Clean all bookmark 清除所有書籤 - + Keymap Manager 鍵盤映射管理器 - + Display keymap editor 顯示鍵盤映射編輯器 - + Create Public Key... 創建公鑰... - + Create a public key 創建公鑰 - + Publickey Manager 公鑰管理器 - + Display publickey manager 顯示公鑰管理器 - + Internal Command 內部命令 - + Display Internal Command window 顯示內部命令窗口 - + Portuguese (Brazil) Português (Brasil) - + Switch to Portuguese (Brazil) Mudar para Português (Brasil) - + German Deutsch - + Switch to German Wechseln Sie zu Deutsch - + Czech čeština - + Switch to Czech Přepnout do češtiny - + Arabic عربي - + Switch to Arabic التبديل إلى العربية - + Theme Color 主題顏色 - + Set theme color, cancel to use default 設置主題顏色,取消使用默認值 - - + + Keyborad Shortcuts Reference 鍵盤快捷鍵參考 - + Display keyborad shortcuts reference 顯示鍵盤快捷鍵參考 - - + + Privacy Statement 隱私聲明 - + Display privacy statement 顯示隱私聲明 - - + + About Python 關於Python - + Display about Python dialog 顯示關於Python對話框 - + Laboratory 實驗室 - - + + SSH Scanning SSH掃描 - + Display SSH scanning dialog 顯示SSH掃描對話框 - + Plugin metaData not found! 未找到插件元數據! - + Plugin api version not found! 未找到插件api版本! - + Plugin api version not match! 插件api版本不匹配! - + Plugin menu not found! 未找到插件菜單! - + Plugin init failed! 插件初始化失敗! - - - - - - - - - - + + + + + + + + + + Broadcast session can't transfer file! 廣播會話無法傳輸文件! - + Select Files to Send as ASCII 選擇要發送的文件為ASCII - - + + Text Files (*.txt);;All Files (*) 文本文件 (*.txt);;所有文件 (*) - + Save Received Data as ASCII 將接收的數據保存為ASCII - + Select Files to Send as BINARY 選擇要發送的文件為二進制 - - - - - - + + + + + + All Files (*) 所有文件 (*) - + Select Files to Send using Kermit 選擇要使用Kermit發送的文件 - + Select Files to Send using Xmodem 選擇要使用Xmodem發送的文件 - + Save Received Files using Xmodem 使用Xmodem保存接收的文件 - + Select Files to Send using Ymodem 選擇要使用Ymodem發送的文件 - + Select Files to Send using Zmodem 選擇要使用Zmodem發送的文件 - + Select a script file 選擇一個腳本文件 - + Python Files (*.py);;All Files (*) Python文件 (*.py);;所有文件 (*) - + Select color 選擇顏色 - + Are you sure to disconnect " 您確定要斷開連接" - + " session? "會話? - + This software is a terminal emulator that provides a secure shell (SSH) connection, telnet connection, serial port connection, and other functions. 此軟件是一個終端仿真器,提供安全外殼(SSH)連接,telnet連接,串口連接和其他功能。 - + This software does not collect any personal information, and does not send any information to the server. 此軟件不收集任何個人信息,也不向服務器發送任何信息。 - + This software does not contain any malicious code, and does not contain any backdoors. 此軟件不包含任何惡意代碼,也不包含任何後門。 - + This software is open source software, you can view the source code on the github website. 此軟件是開源軟件,您可以在github網站上查看源代碼。 - + This software is provided as is, without any warranty. 此軟件按原樣提供,不提供任何保證。 - + If you have any questions or suggestions, please contact the author. 如果您有任何問題或建議,請聯繫作者。 - + Version 版本 - + Commit 提交 - + Date 日期 - - + + Author 作者 - + Website 網站 - + Tab 標籤 - + Arrange sessions in tabs 在標籤中排列會話 - + Tile 平鋪 - + Arrange sessions in non-overlapping tiles 在不重疊的平鋪中排列會話 - + Cascade 級聯 - + Arrange sessions to overlap each other 安排會話互相重疊 - + Simplified Chinese 简体中文 - + Switch to Simplified Chinese 切换到简体中文 - + Traditional Chinese 繁體中文 - + Switch to Traditional Chinese 切換到繁體中文 - + Russian Русский - + Switch to Russian Переключиться на русский - + Korean 한국어 - + Switch to Korean 한국어로 전환 - + Japanese 日本語 - + Switch to Japanese 日本語に切り替える - + French français - + Switch to French Passer au français - + Spanish español - + Switch to Spanish Cambiar a español - + English - + Switch to English - + Light 明亮 - + Switch to light theme 切換到明亮的主題 - + Dark 暗黑 - + Switch to dark theme 切換到暗黑主題 - + Display help 顯示幫助 - + Check Update 檢查更新 - + Check for updates 檢查更新 - - + + About 關於 - + Display about dialog 顯示關於對話框 - + About Qt 關於Qt - + Display about Qt dialog 顯示關於Qt對話框 - + Plugin Info 插件信息 - + Display plugin information dialog 顯示插件信息對話框 - + PrintScreen saved to %1 PrintScreen保存到%1 - + Save Screenshot 保存屏幕截圖 - + Image Files (*.jpg) 圖像文件(*.jpg) - - + + Screenshot saved to %1 屏幕截圖保存到%1 - + Save Session Export 保存會話導出 - + Text Files (*.txt);;HTML Files (*.html) 文本文件(*.txt);;HTML文件(*.html) - + Text Files (*.txt) 文本文件(*.txt) - + HTML Files (*.html) HTML文件(*.html) - + Session Export saved to %1 會話導出保存到%1 - + Session Export failed to save to %1 會話導出保存到%1失敗 - + Select a directory 選擇一個目錄 - + Select a bookmark 選擇一個書籤 - + Are you sure to clean all bookmark? 您確定要清除所有書籤嗎? - + Port 端口 - + Video background is enabled, please enable animation in global options (more system resources) or change background image. 視頻背景已啟用,請在全局選項中啟用動畫(更多系統資源)或更改背景圖像。 - + Session information get failed. 會話信息獲取失敗。 - + Telnet - - + Telnet - + Serial - 串口 - - + Serial 串口 - + Raw - - + Raw - + NamePipe - 命名管道 - - + NamePipe 命名管道 - - + + Local Shell 本地Shell - + Local Shell - 本地Shell - - + Global Shortcuts: 全局快捷鍵: - + show/hide menu bar 顯示/隱藏菜單欄 - + connect to LocalShell 連接到本地Shell - + clone current session 克隆當前會話 - + switch ui to STD mode 切換ui到STD模式 - + switch ui to MINI mode 切換ui到MINI模式 - + switch to previous session 切換到上一個會話 - + switch to next session 切換到下一個會話 - + switch to session [num] 切換到會話[num] - + Go to line start 跳轉到行首 - + Go to line end 跳轉到行尾 - + There are sessions that have not yet been unlocked, please unlock them first. 有會話尚未解鎖,請先解鎖它們。 - + Are you sure to quit? 您確定要退出嗎? @@ -2707,8 +2708,8 @@ - - + + Warning 警告 @@ -2745,7 +2746,7 @@ If you need to use another shell, please create a session through [quick-connect - + The Default Local Shell is not a valid file! 默認本地終端不是有效文件! @@ -2795,7 +2796,7 @@ If you need to use another shell, please create a session through [quick-connect 傳輸 - + The User Plugins Path is not a directory! 用戶插件路徑不是一個目錄! @@ -2869,93 +2870,36 @@ If you need to use another shell, please create a session through [quick-connect 內部命令 - + Copy 複製 - + Paste 粘貼 - + Select All 全選 - + Find 查找 - + Zoom In 放大 - + Zoom Out 縮小 - - Session - - - Bell in session '%1' - 會話 '%1' 中的鈴聲 - - - - TerminalDisplay - - - Size: XXX x XXX - 大小: XXX x XXX - - - - Size: %1 x %2 - 大小: %1 x %2 - - - - Paste multiline text - 粘貼多行文本 - - - - Are you sure you want to paste this text? - 您確定要粘貼此文本嗎? - - - - <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> - <qt>通過按Ctrl+S已經<a href="http://en.wikipedia.org/wiki/Flow_control">暫停</a>輸出。 按<b>Ctrl+Q</b>恢復。</qt> - - - - UrlFilter - - - Follow link (ctrl + click) - 跳轉鏈接 (ctrl + 單擊) - - - - Follow path (ctrl + click) - 跳轉路徑 (ctrl + 單擊) - - - - Vt102Emulation - - - No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. - 沒有可用的鍵盤轉換器。 缺少將按鍵轉換為要發送到終端的字符所需的信息。 - - LockSessionWindow @@ -3484,47 +3428,47 @@ If you need to use another shell, please create a session through [quick-connect QObject - + Un-named Color Scheme 未命名的配色方案 - + Accessible Color Scheme 無障礙配色方案 - + Open Link 打開鏈接 - + Copy Link Address 複製鏈接 - + Send Email To... 發送郵件給... - + Copy Email Address 複製郵件地址 - + Open Path 打開路徑 - + Open Containing Folder 打開包含的文件夾 - + Copy Path 複製路徑 @@ -3587,12 +3531,12 @@ If you need to use another shell, please create a session through [quick-connect QTermWidget - + Color Scheme Error 配色方案錯誤 - + Cannot load color scheme: %1 無法加載配色方案:%1 @@ -3897,20 +3841,20 @@ If you need to use another shell, please create a session through [quick-connect 查找: - - + + Match case 區分大小寫 - - + + Regular expression 正則表達式 - - + + Highlight all matches 高亮所有匹配項 @@ -4252,25 +4196,25 @@ If you need to use another shell, please create a session through [quick-connect SessionsWindow - + Telnet Error telnet錯誤 - + Telnet error: %1. telnet錯誤: %1。 - - + + Serial Error 串口錯誤 - + Serial error: %0 %1. @@ -4279,133 +4223,133 @@ If you need to use another shell, please create a session through [quick-connect %1。 - + Raw Socket Error 原始套接字錯誤 - + Raw Socket error: %1. 原始套接字錯誤: %1。 - + Name Pipe Error 命名管道錯誤 - + Name Pipe error: %1. 命名管道錯誤: %1。 - - + + SSH2 Error SSH2錯誤 - - + + SSH2 error: %1. SSH2錯誤: %1。 - - + + Open URL 打開URL - - + + Cannot open URL %1. 無法打開URL %1。 - + Select Files to Send using Zmodem 選擇要使用Zmodem發送的文件 - + All Files (*) 所有文件 (*) - + Start Local Shell 啟動本地Shell - + Cannot start local shell: %1. 無法啟動本地shell: %1。 - + Serial port %1 has been removed. 串口%1已被移除。 - + Save log... 保存日誌... - + log files (*.log) 日誌文件(*.log) - + Save log 保存日誌 - - - + + + Cannot write file %1: %2. 無法寫入文件%1: %2。 - + Save Raw log... 保存原始日誌... - + binary files (*.bin) 二進制文件(*.bin) - + Save Raw log 保存原始日誌 - + Unlock Session 解鎖會話 - + Wrong password! 密碼錯誤! - + Receive ASCII File 接收ASCII文件 @@ -4662,6 +4606,34 @@ If you need to use another shell, please create a session through [quick-connect 傳輸信息 + + TerminalDisplay + + + Size: XXX x XXX + 大小: XXX x XXX + + + + Size: %1 x %2 + 大小: %1 x %2 + + + + Paste multiline text + 粘貼多行文本 + + + + Are you sure you want to paste this text? + 您確定要粘貼此文本嗎? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>通過按Ctrl+S已經<a href="http://en.wikipedia.org/wiki/Flow_control">暫停</a>輸出。 按<b>Ctrl+Q</b>恢復。</qt> + + UndoStack @@ -4680,6 +4652,27 @@ If you need to use another shell, please create a session through [quick-connect 覆蓋%1字符 + + UrlFilter + + + Follow link (ctrl + click) + 跳轉鏈接 (ctrl + 單擊) + + + + Follow path (ctrl + click) + 跳轉路徑 (ctrl + 單擊) + + + + Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 沒有可用的鍵盤轉換器。 缺少將按鍵轉換為要發送到終端的字符所需的信息。 + + keyMapManager diff --git a/lib/qtermwidget/BlockArray.cpp b/lib/qtermwidget/BlockArray.cpp index dce84b66..28952fe4 100644 --- a/lib/qtermwidget/BlockArray.cpp +++ b/lib/qtermwidget/BlockArray.cpp @@ -1,24 +1,23 @@ /* - This file is part of Konsole, an X terminal. - Copyright (C) 2000 by Stephan Kulow - - Rewritten for QT4 by e_k , Copyright (C)2008 - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. - + This file is part of Konsole, an X terminal. + Copyright (C) 2000 by Stephan Kulow + + Rewritten for QT4 by e_k , Copyright (C)2008 + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include @@ -30,12 +29,12 @@ #include #else if defined(Q_CC_MSVC) #include -#define dup _dup -#define fileno _fileno -#define write _write -#define read _read -#define close _close -#define lseek _lseek +#define dup _dup +#define fileno _fileno +#define write _write +#define read _read +#define close _close +#define lseek _lseek #define ftruncate _chsize #endif #else @@ -48,34 +47,32 @@ static int blocksize = 0; BlockArray::BlockArray() - : size(0), - current(size_t(-1)), - index(size_t(-1)), - lastmap(nullptr), - lastmap_index(size_t(-1)), - lastblock(nullptr), ion(-1), - length(0) -{ + : size(0) + , current(size_t(-1)) + , index(size_t(-1)) + , lastmap(nullptr) + , lastmap_index(size_t(-1)) + , lastblock(nullptr) + , ion(-1) + , length(0) { // lastmap_index = index = current = size_t(-1); if (blocksize == 0) { -#if defined(Q_OS_WIN) + #if defined(Q_OS_WIN) SYSTEM_INFO system_info; GetSystemInfo(&system_info); blocksize = ((sizeof(Block) / system_info.dwPageSize) + 1) * system_info.dwPageSize; -#else + #else blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize(); -#endif + #endif } } -BlockArray::~BlockArray() -{ +BlockArray::~BlockArray() { setHistorySize(0); Q_ASSERT(!lastblock); } -size_t BlockArray::append(Block * block) -{ +size_t BlockArray::append(Block *block) { if (!size) { return size_t(-1); } @@ -110,8 +107,7 @@ size_t BlockArray::append(Block * block) return current; } -size_t BlockArray::newBlock() -{ +size_t BlockArray::newBlock() { if (!size) { return size_t(-1); } @@ -121,13 +117,11 @@ size_t BlockArray::newBlock() return index + 1; } -Block * BlockArray::lastBlock() const -{ - return lastblock; +Block *BlockArray::lastBlock() const { + return lastblock; } -bool BlockArray::has(size_t i) const -{ +bool BlockArray::has(size_t i) const { if (i == index + 1) { return true; } @@ -141,8 +135,7 @@ bool BlockArray::has(size_t i) const return true; } -const Block * BlockArray::at(size_t i) -{ +const Block *BlockArray::at(size_t i) { if (i == index + 1) { return lastblock; } @@ -156,9 +149,9 @@ const Block * BlockArray::at(size_t i) return nullptr; } -// if (index - i >= length) { -// return 0; -// } + //if (index - i >= length) { + // return 0; + //} size_t j = i; // (current - (index - i) + (index/size+1)*size) % size ; @@ -166,9 +159,9 @@ const Block * BlockArray::at(size_t i) unmap(); #if defined(Q_OS_WIN) - Block * block = (Block *)VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + Block *block = (Block *)VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #else - Block * block = (Block *)mmap(nullptr, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); + Block *block = (Block *)mmap(nullptr, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); #endif if (block == (Block *)-1) { @@ -182,30 +175,26 @@ const Block * BlockArray::at(size_t i) return block; } -void BlockArray::unmap() -{ +void BlockArray::unmap() { if (lastmap) { -#if defined(Q_OS_WIN) - int res = 0; - VirtualFree((VOID *) lastmap, 0, MEM_RELEASE ); -#else + #if defined(Q_OS_WIN) + VirtualFree((VOID *)lastmap, 0, MEM_RELEASE); + #else int res = munmap((char *)lastmap, blocksize); -#endif if (res < 0) { perror("munmap"); } + #endif } lastmap = nullptr; lastmap_index = size_t(-1); } -bool BlockArray::setSize(size_t newsize) -{ +bool BlockArray::setSize(size_t newsize) { return setHistorySize(newsize * 1024 / blocksize); } -bool BlockArray::setHistorySize(size_t newsize) -{ +bool BlockArray::setHistorySize(size_t newsize) { if (size == newsize) { return false; } @@ -216,7 +205,7 @@ bool BlockArray::setHistorySize(size_t newsize) delete lastblock; lastblock = nullptr; if (ion >= 0) { - close(ion); + close(ion); } ion = -1; current = size_t(-1); @@ -224,12 +213,12 @@ bool BlockArray::setHistorySize(size_t newsize) } if (!size) { - FILE * tmp = tmpfile(); + FILE *tmp = tmpfile(); if (!tmp) { perror("konsole: cannot open temp file.\n"); } else { ion = dup(fileno(tmp)); - if (ion<0) { + if (ion < 0) { perror("konsole: cannot dup temp file.\n"); fclose(tmp); } @@ -251,7 +240,7 @@ bool BlockArray::setHistorySize(size_t newsize) return false; } else { decreaseBuffer(newsize); - int f = ftruncate(ion, length*blocksize); + int f = ftruncate(ion, length * blocksize); Q_UNUSED(f); size = newsize; @@ -259,8 +248,7 @@ bool BlockArray::setHistorySize(size_t newsize) } } -void moveBlock(FILE * fion, int cursor, int newpos, char * buffer2) -{ +void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2) { int res = fseek(fion, cursor * blocksize, SEEK_SET); if (res) { perror("fseek"); @@ -278,11 +266,10 @@ void moveBlock(FILE * fion, int cursor, int newpos, char * buffer2) if (res != 1) { perror("fwrite"); } - // printf("moving block %d to %d\n", cursor, newpos); + //printf("moving block %d to %d\n", cursor, newpos); } -void BlockArray::decreaseBuffer(size_t newsize) -{ +void BlockArray::decreaseBuffer(size_t newsize) { if (index < newsize) { // still fits in whole return; } @@ -294,11 +281,11 @@ void BlockArray::decreaseBuffer(size_t newsize) } // The Block constructor could do something in future... - char * buffer1 = new char[blocksize]; + char *buffer1 = new char[blocksize]; - FILE * fion = fdopen(dup(ion), "w+b"); + FILE *fion = fdopen(dup(ion), "w+b"); if (!fion) { - delete [] buffer1; + delete[] buffer1; perror("fdopen/dup"); return; } @@ -311,7 +298,7 @@ void BlockArray::decreaseBuffer(size_t newsize) } size_t oldpos; - for (size_t i = 0, cursor=firstblock; i < newsize; i++) { + for (size_t i = 0, cursor = firstblock; i < newsize; i++) { oldpos = (size + cursor + offset) % size; moveBlock(fion, oldpos, cursor, buffer1); if (oldpos < newsize) { @@ -324,13 +311,12 @@ void BlockArray::decreaseBuffer(size_t newsize) current = newsize - 1; length = newsize; - delete [] buffer1; + delete[] buffer1; fclose(fion); } -void BlockArray::increaseBuffer() -{ +void BlockArray::increaseBuffer() { if (index < size) { // not even wrapped once return; } @@ -341,8 +327,8 @@ void BlockArray::increaseBuffer() } // The Block constructor could do something in future... - char * buffer1 = new char[blocksize]; - char * buffer2 = new char[blocksize]; + char *buffer1 = new char[blocksize]; + char *buffer2 = new char[blocksize]; int runs = 1; int bpr = size; // blocks per run @@ -352,11 +338,11 @@ void BlockArray::increaseBuffer() runs = offset; } - FILE * fion = fdopen(dup(ion), "w+b"); + FILE *fion = fdopen(dup(ion), "w+b"); if (!fion) { perror("fdopen/dup"); - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; return; } @@ -373,7 +359,7 @@ void BlockArray::increaseBuffer() perror("fread"); } int newpos = 0; - for (int j = 1, cursor=firstblock; j < bpr; j++) { + for (int j = 1, cursor = firstblock; j < bpr; j++) { cursor = (cursor + offset) % size; newpos = (cursor - offset + size) % size; moveBlock(fion, cursor, newpos, buffer2); @@ -390,9 +376,8 @@ void BlockArray::increaseBuffer() current = size - 1; length = size; - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; fclose(fion); } - diff --git a/lib/qtermwidget/BlockArray.h b/lib/qtermwidget/BlockArray.h index b3cc6de1..c93e2188 100644 --- a/lib/qtermwidget/BlockArray.h +++ b/lib/qtermwidget/BlockArray.h @@ -1,83 +1,78 @@ /* - This file is part of Konsole, an X terminal. - Copyright (C) 2000 by Stephan Kulow - - Rewritten for QT4 by e_k , Copyright (C)2008 - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + Copyright (C) 2000 by Stephan Kulow + + Rewritten for QT4 by e_k , Copyright (C)2008 + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef BLOCKARRAY_H #define BLOCKARRAY_H - -//#error Do not use in KDE 2.1 - -#define QTERMWIDGET_BLOCKSIZE (1 << 12) -#define ENTRIES (QTERMWIDGET_BLOCKSIZE - sizeof(size_t)) +#define QTERMWIDGET_BLOCKSIZE (1 << 12) +#define ENTRIES (QTERMWIDGET_BLOCKSIZE - sizeof(size_t)) struct Block { unsigned char data[ENTRIES] = {}; size_t size = 0; }; -// /////////////////////////////////////////////////////// - class BlockArray { public: /** - * Creates a history file for holding - * maximal size blocks. If more blocks - * are requested, then it drops earlier - * added ones. - */ + * Creates a history file for holding + * maximal size blocks. If more blocks + * are requested, then it drops earlier + * added ones. + */ BlockArray(); /// destructor ~BlockArray(); /** - * adds the Block at the end of history. - * This may drop other blocks. - * - * The ownership on the block is transferred. - * An unique index number is returned for accessing - * it later (if not yet dropped then) - * - * Note, that the block may be dropped completely - * if history is turned off. - */ + * adds the Block at the end of history. + * This may drop other blocks. + * + * The ownership on the block is transferred. + * An unique index number is returned for accessing + * it later (if not yet dropped then) + * + * Note, that the block may be dropped completely + * if history is turned off. + */ size_t append(Block * block); /** - * gets the block at the index. Function may return - * 0 if the block isn't available any more. - * - * The returned block is strictly readonly as only - * mapped in memory - and will be invalid on the next - * operation on this class. - */ + * gets the block at the index. Function may return + * 0 if the block isn't available any more. + * + * The returned block is strictly readonly as only + * mapped in memory - and will be invalid on the next + * operation on this class. + */ const Block * at(size_t index); /** - * reorders blocks as needed. If newsize is null, - * the history is emptied completely. The indices - * returned on append won't change their semantic, - * but they may not be valid after this call. - */ + * reorders blocks as needed. If newsize is null, + * the history is emptied completely. The indices + * returned on append won't change their semantic, + * but they may not be valid after this call. + */ bool setHistorySize(size_t newsize); size_t newBlock(); @@ -85,9 +80,9 @@ class BlockArray { Block * lastBlock() const; /** - * Convenient function to set the size in KBytes - * instead of blocks - */ + * Convenient function to set the size in KBytes + * instead of blocks + */ bool setSize(size_t newsize); size_t len() const { diff --git a/lib/qtermwidget/CharWidth.cpp b/lib/qtermwidget/CharWidth.cpp index 0737f0f6..715ac274 100644 --- a/lib/qtermwidget/CharWidth.cpp +++ b/lib/qtermwidget/CharWidth.cpp @@ -1,36 +1,30 @@ #include "CharWidth.h" -CharWidth::CharWidth(QFont font) -{ +CharWidth::CharWidth(QFont font) { fm = new QFontMetrics(font); } -CharWidth::~CharWidth() -{ +CharWidth::~CharWidth() { delete fm; } -void CharWidth::setFont(QFont font) -{ +void CharWidth::setFont(QFont font) { delete fm; fm = new QFontMetrics(font); } -int CharWidth::font_width(wchar_t ucs) -{ +int CharWidth::font_width(wchar_t ucs) { if(ucs <= 0xffff) return fm->horizontalAdvance(QString(QChar(ucs)),1)/fm->horizontalAdvance("0",1); else return unicode_width(ucs); } -int CharWidth::font_width(const QChar & c) -{ +int CharWidth::font_width(const QChar & c) { return fm->horizontalAdvance(c,1)/fm->horizontalAdvance("0",1); } -int CharWidth::string_font_width( const std::wstring & wstr ) -{ +int CharWidth::string_font_width( const std::wstring & wstr ) { int width = 0; for (auto & c : wstr) { width += font_width(c); @@ -38,8 +32,7 @@ int CharWidth::string_font_width( const std::wstring & wstr ) return width; } -int CharWidth::string_font_width( const QString & str ) -{ +int CharWidth::string_font_width( const QString & str ) { int width = 0; for (auto & c : str) { width += font_width(c.unicode()); @@ -47,8 +40,7 @@ int CharWidth::string_font_width( const QString & str ) return width; } -int CharWidth::unicode_width(wchar_t ucs, bool fix_width) -{ +int CharWidth::unicode_width(wchar_t ucs, bool fix_width) { utf8proc_category_t cat = utf8proc_category( ucs ); if (cat == UTF8PROC_CATEGORY_CO) { // Co: Private use area. libutf8proc makes them zero width, while tmux @@ -65,13 +57,11 @@ int CharWidth::unicode_width(wchar_t ucs, bool fix_width) return utf8proc_charwidth( ucs ); } -int CharWidth::unicode_width(const QChar & c, bool fix_width) -{ +int CharWidth::unicode_width(const QChar & c, bool fix_width) { return unicode_width(c.unicode(),fix_width); } -int CharWidth::string_unicode_width(const std::wstring & wstr, bool fix_width) -{ +int CharWidth::string_unicode_width(const std::wstring & wstr, bool fix_width) { int width = 0; for (auto & c : wstr) { width += unicode_width(c,fix_width); @@ -79,8 +69,7 @@ int CharWidth::string_unicode_width(const std::wstring & wstr, bool fix_width) return width; } -int CharWidth::string_unicode_width(const QString & str, bool fix_width) -{ +int CharWidth::string_unicode_width(const QString & str, bool fix_width) { int width = 0; for (auto & c : str) { width += unicode_width(c.unicode(),fix_width); diff --git a/lib/qtermwidget/Character.h b/lib/qtermwidget/Character.h index d657e22f..0c7c8cd7 100644 --- a/lib/qtermwidget/Character.h +++ b/lib/qtermwidget/Character.h @@ -1,23 +1,23 @@ /* - This file is part of Konsole, KDE's terminal. - - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, KDE's terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef CHARACTER_H #define CHARACTER_H @@ -55,105 +55,102 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2); class Character { public: - /** - * Constructs a new character. - * - * @param _c The unicode character value of this character. - * @param _f The foreground color used to draw the character. - * @param _b The color used to draw the character's background. - * @param _r A set of rendition flags which specify how this character is to be drawn. - */ - inline Character(quint16 _c = ' ', + /** + * Constructs a new character. + * + * @param _c The unicode character value of this character. + * @param _f The foreground color used to draw the character. + * @param _b The color used to draw the character's background. + * @param _r A set of rendition flags which specify how this character is to be drawn. + */ + inline Character(quint16 _c = ' ', CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), quint8 _r = DEFAULT_RENDITION) - : character(_c), rendition(_r), foregroundColor(_f), backgroundColor(_b) {} + : character(_c) + , rendition(_r) + , foregroundColor(_f) + , backgroundColor(_b) { + } + + union { + /** The unicode character value for this character. */ + wchar_t character; + /** + * Experimental addition which allows a single Character instance to contain more than + * one unicode character. + * + * charSequence is a hash code which can be used to look up the unicode + * character sequence in the ExtendedCharTable used to create the sequence. + */ + quint16 charSequence; + }; + + /** A combination of RENDITION flags which specify options for drawing the character. */ + quint8 rendition; + + /** The foreground color used to draw this character. */ + CharacterColor foregroundColor; + /** The color used to draw this character's background. */ + CharacterColor backgroundColor; - union - { - /** The unicode character value for this character. */ - wchar_t character; /** - * Experimental addition which allows a single Character instance to contain more than - * one unicode character. - * - * charSequence is a hash code which can be used to look up the unicode - * character sequence in the ExtendedCharTable used to create the sequence. + * Returns true if this character has a transparent background when + * it is drawn with the specified @p palette. + */ + bool isTransparent(const ColorEntry* palette) const; + /** + * Returns true if this character should always be drawn in bold when + * it is drawn with the specified @p palette, independent of whether + * or not the character has the RE_BOLD rendition flag. + */ + ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; + + /** + * returns true if the format (color, rendition flag) of the compared characters is equal */ - quint16 charSequence; - }; - - /** A combination of RENDITION flags which specify options for drawing the character. */ - quint8 rendition; - - /** The foreground color used to draw this character. */ - CharacterColor foregroundColor; - /** The color used to draw this character's background. */ - CharacterColor backgroundColor; - - /** - * Returns true if this character has a transparent background when - * it is drawn with the specified @p palette. - */ - bool isTransparent(const ColorEntry* palette) const; - /** - * Returns true if this character should always be drawn in bold when - * it is drawn with the specified @p palette, independent of whether - * or not the character has the RE_BOLD rendition flag. - */ - ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; - - /** - * returns true if the format (color, rendition flag) of the compared characters is equal - */ - bool equalsFormat(const Character &other) const; - - /** - * Compares two characters and returns true if they have the same unicode character value, - * rendition and colors. - */ - friend bool operator == (const Character& a, const Character& b); - /** - * Compares two characters and returns true if they have different unicode character values, - * renditions or colors. - */ - friend bool operator != (const Character& a, const Character& b); + bool equalsFormat(const Character &other) const; + + /** + * Compares two characters and returns true if they have the same unicode character value, + * rendition and colors. + */ + friend bool operator == (const Character& a, const Character& b); + /** + * Compares two characters and returns true if they have different unicode character values, + * renditions or colors. + */ + friend bool operator != (const Character& a, const Character& b); }; -inline bool operator == (const Character& a, const Character& b) -{ - return a.character == b.character && - a.rendition == b.rendition && - a.foregroundColor == b.foregroundColor && - a.backgroundColor == b.backgroundColor; +inline bool operator == (const Character& a, const Character& b) { + return a.character == b.character && + a.rendition == b.rendition && + a.foregroundColor == b.foregroundColor && + a.backgroundColor == b.backgroundColor; } -inline bool operator != (const Character& a, const Character& b) -{ - return a.character != b.character || - a.rendition != b.rendition || - a.foregroundColor != b.foregroundColor || - a.backgroundColor != b.backgroundColor; +inline bool operator != (const Character& a, const Character& b) { + return a.character != b.character || + a.rendition != b.rendition || + a.foregroundColor != b.foregroundColor || + a.backgroundColor != b.backgroundColor; } -inline bool Character::isTransparent(const ColorEntry* base) const -{ - return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && - base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) - || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && - base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); +inline bool Character::isTransparent(const ColorEntry* base) const { + return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && + base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) + || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && + base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } -inline bool Character::equalsFormat(const Character& other) const -{ - return - backgroundColor==other.backgroundColor && - foregroundColor==other.foregroundColor && - rendition==other.rendition; +inline bool Character::equalsFormat(const Character& other) const { + return backgroundColor==other.backgroundColor && + foregroundColor==other.foregroundColor && + rendition==other.rendition; } -inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const -{ +inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const { if (backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) return base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].fontWeight; else if (backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) @@ -162,9 +159,6 @@ inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) cons return ColorEntry::UseCurrentFormat; } -extern unsigned short vt100_graphics[32]; - - /** * A table which stores sequences of unicode characters, referenced * by hash keys. The hash key itself is the same size as a unicode diff --git a/lib/qtermwidget/CharacterColor.h b/lib/qtermwidget/CharacterColor.h index eae90220..5ffb9ccb 100644 --- a/lib/qtermwidget/CharacterColor.h +++ b/lib/qtermwidget/CharacterColor.h @@ -1,23 +1,23 @@ /* - This file is part of Konsole, KDE's terminal. - - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, KDE's terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef CHARACTERCOLOR_H #define CHARACTERCOLOR_H @@ -40,56 +40,53 @@ class ColorEntry { public: - /** Specifies the weight to use when drawing text with this color. */ - enum FontWeight - { - /** Always draw text in this color with a bold weight. */ - Bold, - /** Always draw text in this color with a normal weight. */ - Normal, + /** Specifies the weight to use when drawing text with this color. */ + enum FontWeight { + /** Always draw text in this color with a bold weight. */ + Bold, + /** Always draw text in this color with a normal weight. */ + Normal, + /** + * Use the current font weight set by the terminal application. + * This is the default behavior. + */ + UseCurrentFormat + }; + /** - * Use the current font weight set by the terminal application. - * This is the default behavior. + * Constructs a new color palette entry. + * + * @param c The color value for this entry. + * @param tr Specifies that the color should be transparent when used as a background color. + * @param weight Specifies the font weight to use when drawing text with this color. */ - UseCurrentFormat - }; - - /** - * Constructs a new color palette entry. - * - * @param c The color value for this entry. - * @param tr Specifies that the color should be transparent when used as a background color. - * @param weight Specifies the font weight to use when drawing text with this color. - */ - ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) - : color(c), transparent(tr), fontWeight(weight) {} - - /** - * Constructs a new color palette entry with an undefined color, and - * with the transparent and bold flags set to false. - */ - ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} - - /** The color value of this entry for display. */ - QColor color; - - /** - * If true character backgrounds using this color should be transparent. - * This is not applicable when the color is used to render text. - */ - bool transparent; - /** - * Specifies the font weight to use when drawing text with this color. - * This is not applicable when the color is used to draw a character's background. - */ - FontWeight fontWeight; -}; + ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) + : color(c), transparent(tr), fontWeight(weight) {} + /** + * Constructs a new color palette entry with an undefined color, and + * with the transparent and bold flags set to false. + */ + ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} -// Attributed Character Representations /////////////////////////////// + /** The color value of this entry for display. */ + QColor color; + + /** + * If true character backgrounds using this color should be transparent. + * This is not applicable when the color is used to render text. + */ + bool transparent; + /** + * Specifies the font weight to use when drawing text with this color. + * This is not applicable when the color is used to draw a character's background. + */ + FontWeight fontWeight; +}; -// Colors +// Attributed Character Representations +// Colors #define BASE_COLORS (2+8) #define INTENSITIES 2 #define TABLE_COLORS (INTENSITIES*BASE_COLORS) @@ -99,7 +96,6 @@ class ColorEntry //a standard set of colors using black text on a white background. //defined in TerminalDisplay.cpp - extern const ColorEntry base_color_table[TABLE_COLORS]; /* CharacterColor is a union of the various color spaces. @@ -117,7 +113,6 @@ extern const ColorEntry base_color_table[TABLE_COLORS]; Default colour space has two separate colours, namely default foreground and default background colour. */ - #define COLOR_SPACE_UNDEFINED 0 #define COLOR_SPACE_DEFAULT 1 #define COLOR_SPACE_SYSTEM 2 @@ -132,167 +127,157 @@ class CharacterColor friend class Character; public: - /** Constructs a new CharacterColor whose color and color space are undefined. */ - CharacterColor() - : _colorSpace(COLOR_SPACE_UNDEFINED), - _u(0), - _v(0), - _w(0) - {} - - /** - * Constructs a new CharacterColor using the specified @p colorSpace and with - * color value @p co - * - * The meaning of @p co depends on the @p colorSpace used. - * - * TODO : Document how @p co relates to @p colorSpace - * - * TODO : Add documentation about available color spaces. - */ - CharacterColor(quint8 colorSpace, int co) - : _colorSpace(colorSpace), - _u(0), - _v(0), - _w(0) - { - switch (colorSpace) - { - case COLOR_SPACE_DEFAULT: - _u = co & 1; - break; - case COLOR_SPACE_SYSTEM: - _u = co & 7; - _v = (co >> 3) & 1; - break; - case COLOR_SPACE_256: - _u = co & 255; - break; - case COLOR_SPACE_RGB: - _u = co >> 16; - _v = co >> 8; - _w = co; - break; - default: - _colorSpace = COLOR_SPACE_UNDEFINED; + /** Constructs a new CharacterColor whose color and color space are undefined. */ + CharacterColor() + : _colorSpace(COLOR_SPACE_UNDEFINED) + , _u(0) + , _v(0) + , _w(0) { } - } - - CharacterColor(quint8 colorSpace, QColor color) - : _colorSpace(colorSpace), - _u(0), - _v(0), - _w(0) - { - switch (colorSpace) - { - case COLOR_SPACE_RGB: - _u = color.red(); - _v = color.green(); - _w = color.blue(); - break; - default: - _colorSpace = COLOR_SPACE_UNDEFINED; + + /** + * Constructs a new CharacterColor using the specified @p colorSpace and with + * color value @p co + * + * The meaning of @p co depends on the @p colorSpace used. + * + * TODO : Document how @p co relates to @p colorSpace + * + * TODO : Add documentation about available color spaces. + */ + CharacterColor(quint8 colorSpace, int co) + : _colorSpace(colorSpace) + , _u(0) + , _v(0) + , _w(0) { + switch (colorSpace) { + case COLOR_SPACE_DEFAULT: + _u = co & 1; + break; + case COLOR_SPACE_SYSTEM: + _u = co & 7; + _v = (co >> 3) & 1; + break; + case COLOR_SPACE_256: + _u = co & 255; + break; + case COLOR_SPACE_RGB: + _u = co >> 16; + _v = co >> 8; + _w = co; + break; + default: + _colorSpace = COLOR_SPACE_UNDEFINED; + } } - } - /** - * Returns true if this character color entry is valid. - */ - bool isValid() const - { + CharacterColor(quint8 colorSpace, QColor color) + : _colorSpace(colorSpace) + , _u(0) + , _v(0) + , _w(0) { + switch (colorSpace) { + case COLOR_SPACE_RGB: + _u = color.red(); + _v = color.green(); + _w = color.blue(); + break; + default: + _colorSpace = COLOR_SPACE_UNDEFINED; + break; + } + } + + /** + * Returns true if this character color entry is valid. + */ + bool isValid() const { return _colorSpace != COLOR_SPACE_UNDEFINED; - } - - /** - * Set the value of this color from a normal system color to the corresponding intensive - * system color if it's not already an intensive system color. - * - * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM - * color spaces. - */ - void setIntensive(); - - /** - * Returns the color within the specified color @p palette - * - * The @p palette is only used if this color is one of the 16 system colors, otherwise - * it is ignored. - */ - QColor color(const ColorEntry* palette) const; - - /** - * Compares two colors and returns true if they represent the same color value and - * use the same color space. - */ - friend bool operator == (const CharacterColor& a, const CharacterColor& b); - /** - * Compares two colors and returns true if they represent different color values - * or use different color spaces. - */ - friend bool operator != (const CharacterColor& a, const CharacterColor& b); + } + + /** + * Set the value of this color from a normal system color to the corresponding intensive + * system color if it's not already an intensive system color. + * + * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM + * color spaces. + */ + void setIntensive(); + + /** + * Returns the color within the specified color @p palette + * + * The @p palette is only used if this color is one of the 16 system colors, otherwise + * it is ignored. + */ + QColor color(const ColorEntry* palette) const; + + /** + * Compares two colors and returns true if they represent the same color value and + * use the same color space. + */ + friend bool operator == (const CharacterColor& a, const CharacterColor& b); + /** + * Compares two colors and returns true if they represent different color values + * or use different color spaces. + */ + friend bool operator != (const CharacterColor& a, const CharacterColor& b); private: - quint8 _colorSpace; + quint8 _colorSpace; - // bytes storing the character color - quint8 _u; - quint8 _v; - quint8 _w; + // bytes storing the character color + quint8 _u; + quint8 _v; + quint8 _w; }; -inline bool operator == (const CharacterColor& a, const CharacterColor& b) -{ - return a._colorSpace == b._colorSpace && - a._u == b._u && - a._v == b._v && - a._w == b._w; +inline bool operator == (const CharacterColor& a, const CharacterColor& b) { + return a._colorSpace == b._colorSpace && + a._u == b._u && + a._v == b._v && + a._w == b._w; } -inline bool operator != (const CharacterColor& a, const CharacterColor& b) -{ + +inline bool operator != (const CharacterColor& a, const CharacterColor& b) { return !operator==(a,b); } -inline const QColor color256(quint8 u, const ColorEntry* base) -{ - // 0.. 16: system colors - if (u < 8) return base[u+2 ].color; - u -= 8; - if (u < 8) return base[u+2+BASE_COLORS].color; - u -= 8; - - // 16..231: 6x6x6 rgb color cube - if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, - ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, - ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); - u -= 216; - - // 232..255: gray, leaving out black and white - int gray = u*10+8; return QColor(gray,gray,gray); +inline const QColor color256(quint8 u, const ColorEntry* base) { + // 0.. 16: system colors + if (u < 8) return base[u+2 ].color; + u -= 8; + if (u < 8) return base[u+2+BASE_COLORS].color; + u -= 8; + + // 16..231: 6x6x6 rgb color cube + if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, + ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, + ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); + u -= 216; + + // 232..255: gray, leaving out black and white + int gray = u*10+8; return QColor(gray,gray,gray); } -inline QColor CharacterColor::color(const ColorEntry* base) const -{ - switch (_colorSpace) - { - case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color; - case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color; - case COLOR_SPACE_256: return color256(_u,base); - case COLOR_SPACE_RGB: return {_u,_v,_w}; - case COLOR_SPACE_UNDEFINED: return QColor(); - } - - Q_ASSERT(false); // invalid color space - - return QColor(); +inline QColor CharacterColor::color(const ColorEntry* base) const { + switch (_colorSpace) { + case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color; + case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color; + case COLOR_SPACE_256: return color256(_u,base); + case COLOR_SPACE_RGB: return {_u,_v,_w}; + case COLOR_SPACE_UNDEFINED: return QColor(); + } + + Q_ASSERT(false); // invalid color space + + return QColor(); } -inline void CharacterColor::setIntensive() -{ - if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) - { - _v = 1; - } +inline void CharacterColor::setIntensive() { + if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) { + _v = 1; + } } #endif // CHARACTERCOLOR_H diff --git a/lib/qtermwidget/ColorScheme.cpp b/lib/qtermwidget/ColorScheme.cpp index dd61e487..8b23404e 100644 --- a/lib/qtermwidget/ColorScheme.cpp +++ b/lib/qtermwidget/ColorScheme.cpp @@ -1,91 +1,89 @@ /* - This source file is part of Konsole, a terminal emulator. + This source file is part of Konsole, a terminal emulator. - Copyright 2007-2008 by Robert Knight + Copyright 2007-2008 by Robert Knight - 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 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. + 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "ColorScheme.h" #include "tools.h" #include +#include #include #include -#include -#include -#include -#include #include +#include +#include #include +#include -const ColorEntry ColorScheme::defaultTable[TABLE_COLORS] = - // The following are almost IBM standard color codes, with some slight - // gamma correction for the dim colors to compensate for bright X screens. - // It contains the 8 ansiterm/xterm colors in 2 intensities. -{ - ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( -QColor(0xFF,0xFF,0xFF), true), // Dfore, Dback - ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( -QColor(0xB2,0x18,0x18), false), // Black, Red - ColorEntry( QColor(0x18,0xB2,0x18), false), ColorEntry( -QColor(0xB2,0x68,0x18), false), // Green, Yellow - ColorEntry( QColor(0x18,0x18,0xB2), false), ColorEntry( -QColor(0xB2,0x18,0xB2), false), // Blue, Magenta - ColorEntry( QColor(0x18,0xB2,0xB2), false), ColorEntry( -QColor(0xB2,0xB2,0xB2), false), // Cyan, White +// The following are almost IBM standard color codes, with some slight +// gamma correction for the dim colors to compensate for bright X screens. +// It contains the 8 ansiterm/xterm colors in 2 intensities. +const ColorEntry ColorScheme::defaultTable[TABLE_COLORS] = { + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xFF, 0xFF, 0xFF), true) , // Dfore, Dback + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xB2, 0x18, 0x18), false), // Black, Red + ColorEntry(QColor(0x18, 0xB2, 0x18), false), + ColorEntry(QColor(0xB2, 0x68, 0x18), false), // Green, Yellow + ColorEntry(QColor(0x18, 0x18, 0xB2), false), + ColorEntry(QColor(0xB2, 0x18, 0xB2), false), // Blue, Magenta + ColorEntry(QColor(0x18, 0xB2, 0xB2), false), + ColorEntry(QColor(0xB2, 0xB2, 0xB2), false), // Cyan, White // intensive - ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( -QColor(0xFF,0xFF,0xFF), true), - ColorEntry( QColor(0x68,0x68,0x68), false), ColorEntry( -QColor(0xFF,0x54,0x54), false), - ColorEntry( QColor(0x54,0xFF,0x54), false), ColorEntry( -QColor(0xFF,0xFF,0x54), false), - ColorEntry( QColor(0x54,0x54,0xFF), false), ColorEntry( -QColor(0xFF,0x54,0xFF), false), - ColorEntry( QColor(0x54,0xFF,0xFF), false), ColorEntry( -QColor(0xFF,0xFF,0xFF), false) + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xFF, 0xFF, 0xFF), true) , + ColorEntry(QColor(0x68, 0x68, 0x68), false), + ColorEntry(QColor(0xFF, 0x54, 0x54), false), + ColorEntry(QColor(0x54, 0xFF, 0x54), false), + ColorEntry(QColor(0xFF, 0xFF, 0x54), false), + ColorEntry(QColor(0x54, 0x54, 0xFF), false), + ColorEntry(QColor(0xFF, 0x54, 0xFF), false), + ColorEntry(QColor(0x54, 0xFF, 0xFF), false), + ColorEntry(QColor(0xFF, 0xFF, 0xFF), false), }; -const char* const ColorScheme::colorNames[TABLE_COLORS] = -{ - "Foreground", - "Background", - "Color0", - "Color1", - "Color2", - "Color3", - "Color4", - "Color5", - "Color6", - "Color7", - "ForegroundIntense", - "BackgroundIntense", - "Color0Intense", - "Color1Intense", - "Color2Intense", - "Color3Intense", - "Color4Intense", - "Color5Intense", - "Color6Intense", - "Color7Intense" +const char *const ColorScheme::colorNames[TABLE_COLORS] = { + "Foreground", + "Background", + "Color0", + "Color1", + "Color2", + "Color3", + "Color4", + "Color5", + "Color6", + "Color7", + "ForegroundIntense", + "BackgroundIntense", + "Color0Intense", + "Color1Intense", + "Color2Intense", + "Color3Intense", + "Color4Intense", + "Color5Intense", + "Color6Intense", + "Color7Intense" }; + // dummy silently comment out the tr_NOOP #define tr_NOOP -const char* const ColorScheme::translatedColorNames[TABLE_COLORS] = -{ +const char *const ColorScheme::translatedColorNames[TABLE_COLORS] = { tr_NOOP("Foreground"), tr_NOOP("Background"), tr_NOOP("Color 1"), @@ -108,121 +106,123 @@ const char* const ColorScheme::translatedColorNames[TABLE_COLORS] = tr_NOOP("Color 8 (Intense)") }; -ColorScheme::ColorScheme() -{ +ColorScheme::ColorScheme() { _table = nullptr; _randomTable = nullptr; _opacity = 1.0; } -ColorScheme::ColorScheme(const ColorScheme& other) - : _opacity(other._opacity) - ,_table(nullptr) - ,_randomTable(nullptr) -{ + +ColorScheme::ColorScheme(const ColorScheme &other) + : _opacity(other._opacity), _table(nullptr), _randomTable(nullptr) { setName(other.name()); setDescription(other.description()); - if ( other._table != nullptr ) - { - for ( int i = 0 ; i < TABLE_COLORS ; i++ ) - setColorTableEntry(i,other._table[i]); + if(other._table != nullptr) { + for (int i = 0; i < TABLE_COLORS; i++) + setColorTableEntry(i, other._table[i]); } - if ( other._randomTable != nullptr ) - { - for ( int i = 0 ; i < TABLE_COLORS ; i++ ) - { - const RandomizationRange& range = other._randomTable[i]; - setRandomizationRange(i,range.hue,range.saturation,range.value); + if(other._randomTable != nullptr) { + for(int i = 0; i < TABLE_COLORS; i++) { + const RandomizationRange &range = other._randomTable[i]; + setRandomizationRange(i, range.hue, range.saturation, range.value); } } } -ColorScheme::~ColorScheme() -{ + +ColorScheme::~ColorScheme() { delete[] _table; delete[] _randomTable; } -void ColorScheme::setDescription(const QString& description) { _description = description; } -QString ColorScheme::description() const { return _description; } +void ColorScheme::setDescription(const QString &description) { + _description = description; +} + +QString ColorScheme::description() const { + return _description; +} + +void ColorScheme::setName(const QString &name) { + _name = name; +} -void ColorScheme::setName(const QString& name) { _name = name; } -QString ColorScheme::name() const { return _name; } +QString ColorScheme::name() const { + return _name; +} -void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry) -{ - Q_ASSERT( index >= 0 && index < TABLE_COLORS ); +void ColorScheme::setColorTableEntry(int index, const ColorEntry &entry) { + Q_ASSERT(index >= 0 && index < TABLE_COLORS); - if ( !_table ) - { + if (!_table) { _table = new ColorEntry[TABLE_COLORS]; - for (int i=0;i= 0 && index < TABLE_COLORS ); - ColorEntry entry = colorTable()[index]; +ColorEntry ColorScheme::colorEntry(int index) const { + Q_ASSERT(index >= 0 && index < TABLE_COLORS); - if ( _randomTable != nullptr && - !_randomTable[index].isNull() ) - { - const RandomizationRange& range = _randomTable[index]; + ColorEntry entry = colorTable()[index]; + if (_randomTable != nullptr && !_randomTable[index].isNull()) { + const RandomizationRange &range = _randomTable[index]; - int hueDifference = range.hue ? QRandomGenerator::global()->bounded(range.hue) - range.hue/2 : 0; - int saturationDifference = range.saturation ? QRandomGenerator::global()->bounded(range.saturation) - range.saturation/2 : 0; - int valueDifference = range.value ? QRandomGenerator::global()->bounded(range.value) - range.value/2 : 0; + int hueDifference = range.hue + ? QRandomGenerator::global()->bounded(range.hue) - range.hue / 2 + : 0; + int saturationDifference = range.saturation + ? QRandomGenerator::global()->bounded(range.saturation) - + range.saturation / 2 + : 0; + int valueDifference = range.value + ? QRandomGenerator::global()->bounded(range.value) - range.value / 2 + : 0; - QColor& color = entry.color; + QColor &color = entry.color; - int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE ); - int newValue = qMin( qAbs(color.value() + valueDifference) , 255 ); - int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 ); + int newHue = qAbs((color.hue() + hueDifference) % MAX_HUE); + int newValue = qMin(qAbs(color.value() + valueDifference), 255); + int newSaturation = qMin(qAbs(color.saturation() + saturationDifference), 255); - color.setHsv(newHue,newSaturation,newValue); + color.setHsv(newHue, newSaturation, newValue); } return entry; } -void ColorScheme::getColorTable(ColorEntry* table) const -{ - for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + +void ColorScheme::getColorTable(ColorEntry *table) const { + for (int i = 0; i < TABLE_COLORS; i++) table[i] = colorEntry(i); } -bool ColorScheme::randomizedBackgroundColor() const -{ + +bool ColorScheme::randomizedBackgroundColor() const { return _randomTable == nullptr ? false : !_randomTable[1].isNull(); } -void ColorScheme::setRandomizedBackgroundColor(bool randomize) -{ + +void ColorScheme::setRandomizedBackgroundColor(bool randomize) { // the hue of the background colour is allowed to be randomly // adjusted as much as possible. // // the value and saturation are left alone to maintain read-ability - if ( randomize ) - { - setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 ); - } - else - { - if ( _randomTable ) - setRandomizationRange( 1 /* background color index */ , 0 , 0 , 0 ); + if (randomize) { + setRandomizationRange(1 /* background color index */, MAX_HUE, 255, 0); + } else { + if (_randomTable) + setRandomizationRange(1 /* background color index */, 0, 0, 0); } } -void ColorScheme::setRandomizationRange( int index , quint16 hue , quint8 saturation , - quint8 value ) -{ - Q_ASSERT( hue <= MAX_HUE ); - Q_ASSERT( index >= 0 && index < TABLE_COLORS ); +void ColorScheme::setRandomizationRange(int index, quint16 hue, + quint8 saturation, quint8 value) { + Q_ASSERT(hue <= MAX_HUE); + Q_ASSERT(index >= 0 && index < TABLE_COLORS); - if ( _randomTable == nullptr ) + if (_randomTable == nullptr) _randomTable = new RandomizationRange[TABLE_COLORS]; _randomTable[index].hue = hue; @@ -230,48 +230,52 @@ void ColorScheme::setRandomizationRange( int index , quint16 hue , quint8 satura _randomTable[index].saturation = saturation; } -const ColorEntry* ColorScheme::colorTable() const -{ - if ( _table ) +const ColorEntry *ColorScheme::colorTable() const { + if (_table) return _table; else return defaultTable; } -QColor ColorScheme::foregroundColor() const -{ - return colorTable()[0].color; + +QColor ColorScheme::foregroundColor() const { + return colorTable()[0].color; } -QColor ColorScheme::backgroundColor() const -{ - return colorTable()[1].color; + +QColor ColorScheme::backgroundColor() const { + return colorTable()[1].color; } -bool ColorScheme::hasDarkBackground() const -{ - // value can range from 0 - 255, with larger values indicating higher brightness. - // so 127 is in the middle, anything less is deemed 'dark' + +bool ColorScheme::hasDarkBackground() const { + // value can range from 0 - 255, with larger values indicating higher + // brightness. so 127 is in the middle, anything less is deemed 'dark' return backgroundColor().value() < 127; } -void ColorScheme::setOpacity(qreal opacity) { _opacity = opacity; } -qreal ColorScheme::opacity() const { return _opacity; } -void ColorScheme::read(const QString & fileName) -{ +void ColorScheme::setOpacity(qreal opacity) { + _opacity = opacity; +} + +qreal ColorScheme::opacity() const { + return _opacity; +} + +void ColorScheme::read(const QString &fileName) { QSettings s(fileName, QSettings::IniFormat); s.beginGroup(QLatin1String("General")); - _description = s.value(QLatin1String("Description"), QObject::tr("Un-named Color Scheme")).toString(); - _opacity = s.value(QLatin1String("Opacity"),qreal(1.0)).toDouble(); + _description = s.value(QLatin1String("Description"), + QObject::tr("Un-named Color Scheme")).toString(); + _opacity = s.value(QLatin1String("Opacity"), qreal(1.0)).toDouble(); s.endGroup(); - for (int i=0 ; i < TABLE_COLORS ; i++) - { + for (int i = 0; i < TABLE_COLORS; i++) { readColorEntry(&s, i); } } + #if 0 // implemented upstream - user apps -void ColorScheme::read(KConfig& config) -{ +void ColorScheme::read(KConfig& config) { KConfigGroup configGroup = config.group("General"); QString description = configGroup.readEntry("Description", QObject::tr("Un-named Color Scheme")); @@ -279,41 +283,37 @@ void ColorScheme::read(KConfig& config) _description = tr(description.toUtf8()); _opacity = configGroup.readEntry("Opacity",qreal(1.0)); - for (int i=0 ; i < TABLE_COLORS ; i++) - { + for (int i=0 ; i < TABLE_COLORS ; i++) { readColorEntry(config,i); } } -void ColorScheme::write(KConfig& config) const -{ + +void ColorScheme::write(KConfig& config) const { KConfigGroup configGroup = config.group("General"); configGroup.writeEntry("Description",_description); configGroup.writeEntry("Opacity",_opacity); - for (int i=0 ; i < TABLE_COLORS ; i++) - { + for (int i=0 ; i < TABLE_COLORS ; i++) { RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange(); writeColorEntry(config,colorNameForIndex(i),colorTable()[i],random); } } #endif -QString ColorScheme::colorNameForIndex(int index) -{ - Q_ASSERT( index >= 0 && index < TABLE_COLORS ); +QString ColorScheme::colorNameForIndex(int index) { + Q_ASSERT(index >= 0 && index < TABLE_COLORS); return QString::fromLatin1(colorNames[index]); } -QString ColorScheme::translatedColorNameForIndex(int index) -{ - Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + +QString ColorScheme::translatedColorNameForIndex(int index) { + Q_ASSERT(index >= 0 && index < TABLE_COLORS); return QString::fromLatin1(translatedColorNames[index]); } -void ColorScheme::readColorEntry(QSettings * s , int index) -{ +void ColorScheme::readColorEntry(QSettings *s, int index) { QString colorName = colorNameForIndex(index); s->beginGroup(colorName); @@ -326,12 +326,10 @@ void ColorScheme::readColorEntry(QSettings * s , int index) bool ok = false; // XXX: Undocumented(?) QSettings behavior: values with commas are parsed // as QStringList and others QString - if (colorValue.typeId() == QMetaType::QStringList) - { + if (colorValue.typeId() == QMetaType::QStringList) { QStringList rgbList = colorValue.toStringList(); colorStr = rgbList.join(QLatin1Char(',')); - if (rgbList.count() == 3) - { + if (rgbList.count() == 3) { bool parse_ok; ok = true; @@ -342,14 +340,12 @@ void ColorScheme::readColorEntry(QSettings * s , int index) b = rgbList[2].toInt(&parse_ok); ok = ok && parse_ok && (b >= 0 && b <= 0xff); } - } - else - { + } else { colorStr = colorValue.toString(); - QRegularExpression hexColorPattern(QLatin1String("^#[0-9a-f]{6}$"), - QRegularExpression::CaseInsensitiveOption); - if (hexColorPattern.match(colorStr).hasMatch()) - { + QRegularExpression hexColorPattern( + QLatin1String("^#[0-9a-f]{6}$"), + QRegularExpression::CaseInsensitiveOption); + if (hexColorPattern.match(colorStr).hasMatch()) { // Parsing is always ok as already matched by the regexp r = QStringView{colorStr}.mid(1, 2).toInt(nullptr, 16); g = QStringView{colorStr}.mid(3, 2).toInt(nullptr, 16); @@ -357,15 +353,14 @@ void ColorScheme::readColorEntry(QSettings * s , int index) ok = true; } } - if (!ok) - { - qWarning().nospace() << "Invalid color value " << colorStr - << " for " << colorName << ". Fallback to black."; + if (!ok) { + qWarning().nospace() << "Invalid color value " << colorStr << " for " + << colorName << ". Fallback to black."; r = g = b = 0; } entry.color = QColor(r, g, b); - entry.transparent = s->value(QLatin1String("Transparent"),false).toBool(); + entry.transparent = s->value(QLatin1String("Transparent"), false).toBool(); // Deprecated key from KDE 4.0 which set 'Bold' to true to force // a color to be bold or false to use the current format @@ -373,37 +368,37 @@ void ColorScheme::readColorEntry(QSettings * s , int index) // TODO - Add a new tri-state key which allows for bold, normal or // current format if (s->contains(QLatin1String("Bold"))) - entry.fontWeight = s->value(QLatin1String("Bold"),false).toBool() ? ColorEntry::Bold : - ColorEntry::UseCurrentFormat; + entry.fontWeight = s->value(QLatin1String("Bold"), false).toBool() + ? ColorEntry::Bold + : ColorEntry::UseCurrentFormat; - quint16 hue = s->value(QLatin1String("MaxRandomHue"),0).toInt(); - quint8 value = s->value(QLatin1String("MaxRandomValue"),0).toInt(); - quint8 saturation = s->value(QLatin1String("MaxRandomSaturation"),0).toInt(); + quint16 hue = s->value(QLatin1String("MaxRandomHue"), 0).toInt(); + quint8 value = s->value(QLatin1String("MaxRandomValue"), 0).toInt(); + quint8 saturation = s->value(QLatin1String("MaxRandomSaturation"), 0).toInt(); - setColorTableEntry( index , entry ); + setColorTableEntry(index, entry); - if ( hue != 0 || value != 0 || saturation != 0 ) - setRandomizationRange( index , hue , saturation , value ); + if (hue != 0 || value != 0 || saturation != 0) + setRandomizationRange(index, hue, saturation, value); s->endGroup(); } + #if 0 // implemented upstream - user apps -void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry , const RandomizationRange& random) const -{ +void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, + const ColorEntry& entry , const RandomizationRange& random) const { KConfigGroup configGroup(&config,colorName); configGroup.writeEntry("Color",entry.color); configGroup.writeEntry("Transparency",(bool)entry.transparent); - if (entry.fontWeight != ColorEntry::UseCurrentFormat) - { + if (entry.fontWeight != ColorEntry::UseCurrentFormat) { configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); } // record randomization if this color has randomization or // if one of the keys already exists - if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) - { + if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) { configGroup.writeEntry("MaxRandomHue",static_cast(random.hue)); configGroup.writeEntry("MaxRandomValue",static_cast(random.value)); configGroup.writeEntry("MaxRandomSaturation",static_cast(random.saturation)); @@ -438,9 +433,7 @@ void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, co // // -- Robert Knight 21/07/2007 // -AccessibleColorScheme::AccessibleColorScheme() - : ColorScheme() -{ +AccessibleColorScheme::AccessibleColorScheme() : ColorScheme() { #if 0 // It's not finished in konsole and it breaks Qt4 compilation as well // basic attributes @@ -452,8 +445,7 @@ AccessibleColorScheme::AccessibleColorScheme() const KColorScheme colorScheme(QPalette::Active); - QBrush colors[ColorRoleCount] = - { + QBrush colors[ColorRoleCount] = { colorScheme.foreground( colorScheme.NormalText ), colorScheme.background( colorScheme.NormalBackground ), @@ -465,8 +457,7 @@ AccessibleColorScheme::AccessibleColorScheme() colorScheme.foreground( colorScheme.NeutralText ) }; - for ( int i = 0 ; i < TABLE_COLORS ; i++ ) - { + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) { ColorEntry entry; entry.color = colors[ i % ColorRoleCount ].color(); @@ -475,88 +466,77 @@ AccessibleColorScheme::AccessibleColorScheme() #endif } -ColorSchemeManager::ColorSchemeManager() - : _haveLoadedAll(false) -{ +ColorSchemeManager::ColorSchemeManager() + : _haveLoadedAll(false) { } -ColorSchemeManager::~ColorSchemeManager() -{ - QHashIterator iter(_colorSchemes); - while (iter.hasNext()) - { + +ColorSchemeManager::~ColorSchemeManager() { + QHashIterator iter(_colorSchemes); + while (iter.hasNext()) { iter.next(); delete iter.value(); } } -void ColorSchemeManager::loadAllColorSchemes() -{ + +void ColorSchemeManager::loadAllColorSchemes() { QList nativeColorSchemes = listColorSchemes(); QListIterator nativeIter(nativeColorSchemes); - while ( nativeIter.hasNext() ) - { - loadColorScheme( nativeIter.next() ); + while (nativeIter.hasNext()) { + loadColorScheme(nativeIter.next()); } _haveLoadedAll = true; } -QList ColorSchemeManager::allColorSchemes() -{ - if ( !_haveLoadedAll ) - { + +QList ColorSchemeManager::allColorSchemes() { + if (!_haveLoadedAll) { loadAllColorSchemes(); } return _colorSchemes.values(); } -bool ColorSchemeManager::loadCustomColorScheme(const QString& path) -{ +bool ColorSchemeManager::loadCustomColorScheme(const QString &path) { if (path.endsWith(QLatin1String(".colorscheme"))) return loadColorScheme(path); return false; } -void ColorSchemeManager::addCustomColorSchemeDir(const QString& custom_dir) -{ +void ColorSchemeManager::addCustomColorSchemeDir(const QString &custom_dir) { add_custom_color_scheme_dir(custom_dir); } -bool ColorSchemeManager::loadColorScheme(const QString& filePath) -{ - if ( !filePath.endsWith(QLatin1String(".colorscheme")) || !QFile::exists(filePath) ) +bool ColorSchemeManager::loadColorScheme(const QString &filePath) { + if (!filePath.endsWith(QLatin1String(".colorscheme")) || + !QFile::exists(filePath)) return false; QFileInfo info(filePath); - const QString& schemeName = info.baseName(); + const QString &schemeName = info.baseName(); - ColorScheme* scheme = new ColorScheme(); + ColorScheme *scheme = new ColorScheme(); scheme->setName(schemeName); scheme->read(filePath); - if (scheme->name().isEmpty()) - { + if (scheme->name().isEmpty()) { delete scheme; return false; } - if ( !_colorSchemes.contains(schemeName) ) - { - _colorSchemes.insert(schemeName,scheme); - } - else - { + if (!_colorSchemes.contains(schemeName)) { + _colorSchemes.insert(schemeName, scheme); + } else { delete scheme; } return true; } -QList ColorSchemeManager::listColorSchemes() -{ + +QList ColorSchemeManager::listColorSchemes() { QList ret; - for (const QString &scheme_dir : get_color_schemes_dirs()) - { + for (const QString &scheme_dir : get_color_schemes_dirs()) { const QString dname(scheme_dir); QDir dir(dname); QStringList filters; @@ -567,67 +547,62 @@ QList ColorSchemeManager::listColorSchemes() ret << dname + QLatin1Char('/') + i; } return ret; -// return KGlobal::dirs()->findAllResources("data", -// "konsole/*.colorscheme", -// KStandardDirs::NoDuplicates); + //return KGlobal::dirs()->findAllResources("data", + // "konsole/*.colorscheme", + // KStandardDirs::NoDuplicates); } + const ColorScheme ColorSchemeManager::_defaultColorScheme; -const ColorScheme* ColorSchemeManager::defaultColorScheme() const -{ +const ColorScheme *ColorSchemeManager::defaultColorScheme() const { return &_defaultColorScheme; } -bool ColorSchemeManager::deleteColorScheme(const QString& name) -{ - Q_ASSERT( _colorSchemes.contains(name) ); + +bool ColorSchemeManager::deleteColorScheme(const QString &name) { + Q_ASSERT(_colorSchemes.contains(name)); // lookup the path and delete QString path = findColorSchemePath(name); - if ( QFile::remove(path) ) - { + if (QFile::remove(path)) { _colorSchemes.remove(name); return true; - } - else - { + } else { return false; } } -QString ColorSchemeManager::findColorSchemePath(const QString& name) const -{ + +QString ColorSchemeManager::findColorSchemePath(const QString &name) const { const QStringList dirs = get_color_schemes_dirs(); - if ( dirs.isEmpty() ) + if (dirs.isEmpty()) return QString(); const QString dir = dirs.first(); - QString path(dir + QLatin1Char('/')+ name + QLatin1String(".colorscheme")); - if ( !path.isEmpty() ) + QString path(dir + QLatin1Char('/') + name + QLatin1String(".colorscheme")); + if (!path.isEmpty()) return path; - path = dir + QLatin1Char('/')+ name + QLatin1String(".schema"); + path = dir + QLatin1Char('/') + name + QLatin1String(".schema"); return path; } -const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) -{ - if ( name.isEmpty() ) + +const ColorScheme *ColorSchemeManager::findColorScheme(const QString &name) { + if (name.isEmpty()) return defaultColorScheme(); - if ( _colorSchemes.contains(name) ) + if (_colorSchemes.contains(name)) { return _colorSchemes[name]; - else - { + } else { // look for this color scheme QString path = findColorSchemePath(name); - if ( !path.isEmpty() && loadColorScheme(path) ) - { + if (!path.isEmpty() && loadColorScheme(path)) { return findColorScheme(name); } return nullptr; } } + Q_GLOBAL_STATIC(ColorSchemeManager, theColorSchemeManager) -ColorSchemeManager* ColorSchemeManager::instance() -{ +ColorSchemeManager *ColorSchemeManager::instance() { return theColorSchemeManager; } diff --git a/lib/qtermwidget/ColorScheme.h b/lib/qtermwidget/ColorScheme.h index f40c8e8a..9a91ee82 100644 --- a/lib/qtermwidget/ColorScheme.h +++ b/lib/qtermwidget/ColorScheme.h @@ -1,22 +1,22 @@ /* - This source file is part of Konsole, a terminal emulator. - - Copyright 2007-2008 by Robert Knight - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This source file is part of Konsole, a terminal emulator. + + Copyright 2007-2008 by Robert Knight + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef COLORSCHEME_H #define COLORSCHEME_H @@ -60,7 +60,7 @@ class ColorScheme QString name() const; #if 0 -// Implemented upstream - in user apps + // Implemented upstream - in user apps /** Reads the color scheme from the specified configuration source */ void read(KConfig& config); /** Writes the color scheme to the specified configuration source */ @@ -140,13 +140,11 @@ class ColorScheme private: // specifies how much a particular color can be randomized by - class RandomizationRange - { + class RandomizationRange { public: RandomizationRange() : hue(0) , saturation(0) , value(0) {} - bool isNull() const - { + bool isNull() const { return ( hue == 0 && saturation == 0 && value == 0 ); } @@ -160,7 +158,7 @@ class ColorScheme const ColorEntry* colorTable() const; #if 0 -// implemented upstream - user apps + // implemented upstream - user apps // reads a single colour entry from a KConfig source // and sets the palette entry at 'index' to the entry read. void readColorEntry(KConfig& config , int index); diff --git a/lib/qtermwidget/DefaultTranslatorText.h b/lib/qtermwidget/DefaultTranslatorText.h deleted file mode 100644 index e47417c5..00000000 --- a/lib/qtermwidget/DefaultTranslatorText.h +++ /dev/null @@ -1,2 +0,0 @@ -"keyboard \"Fallback Key Translator\"\n" -"key Tab : \"\\t\" \0" diff --git a/lib/qtermwidget/Emulation.cpp b/lib/qtermwidget/Emulation.cpp index e51272c9..fa51be31 100644 --- a/lib/qtermwidget/Emulation.cpp +++ b/lib/qtermwidget/Emulation.cpp @@ -1,24 +1,23 @@ /* - Copyright 2007-2008 Robert Knight - Copyright 1997,1998 by Lars Doelle - Copyright 1996 by Matthias Ettrich - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2007-2008 Robert Knight + Copyright 1997,1998 by Lars Doelle + Copyright 1996 by Matthias Ettrich + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ - #include "Emulation.h" #include @@ -35,200 +34,184 @@ #include "KeyboardTranslator.h" #include "Screen.h" -#include "TerminalCharacterDecoder.h" #include "ScreenWindow.h" +#include "TerminalCharacterDecoder.h" -Emulation::Emulation() : - _currentScreen(nullptr), - _keyTranslator(nullptr), - _enableHandleCtrlC(false), - _usesMouse(false), - _bracketedPasteMode(false), - _fromUtf8(QStringEncoder::Utf16) -{ - // create screens with a default size - _screen[0] = new Screen(40,80); - _screen[1] = new Screen(40,80); - _currentScreen = _screen[0]; +Emulation::Emulation() + : _currentScreen(nullptr) + , _keyTranslator(nullptr) + , _enableHandleCtrlC(false) + , _usesMouse(false) + , _bracketedPasteMode(false) + , _fromUtf8(QStringEncoder::Utf16) { + // create screens with a default size + _screen[0] = new Screen(40, 80); + _screen[1] = new Screen(40, 80); + _currentScreen = _screen[0]; - QObject::connect(&_bulkTimer1, &QTimer::timeout, this, &Emulation::showBulk); - QObject::connect(&_bulkTimer2, &QTimer::timeout, this, &Emulation::showBulk); + connect(&_bulkTimer1, &QTimer::timeout, this, &Emulation::showBulk); + connect(&_bulkTimer2, &QTimer::timeout, this, &Emulation::showBulk); - // listen for mouse status changes - connect(this, &Emulation::programUsesMouseChanged, - this, &Emulation::usesMouseChanged); - connect(this, &Emulation::programBracketedPasteModeChanged, - this, &Emulation::bracketedPasteModeChanged); + // listen for mouse status changes + connect(this, &Emulation::programUsesMouseChanged, this, + &Emulation::usesMouseChanged); + connect(this, &Emulation::programBracketedPasteModeChanged, this, + &Emulation::bracketedPasteModeChanged); - connect(this, &Emulation::cursorChanged, this, [this] (KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { - emit profileChangeCommandReceived(QString(QLatin1String("CursorShape=%1;BlinkingCursorEnabled=%2")) - .arg(static_cast(cursorShape)).arg(blinkingCursorEnabled) ); - }); + connect(this, &Emulation::cursorChanged, this, + [this](KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { + emit profileChangeCommandReceived( + QString(QLatin1String("CursorShape=%1;BlinkingCursorEnabled=%2")) + .arg(static_cast(cursorShape)) + .arg(blinkingCursorEnabled)); + }); } -bool Emulation::programUsesMouse() const -{ - return _usesMouse; +bool Emulation::programUsesMouse() const { + return _usesMouse; } -void Emulation::usesMouseChanged(bool usesMouse) -{ - _usesMouse = usesMouse; +void Emulation::usesMouseChanged(bool usesMouse) { + _usesMouse = usesMouse; } -bool Emulation::programBracketedPasteMode() const -{ +bool Emulation::programBracketedPasteMode() const { return _bracketedPasteMode; } -void Emulation::bracketedPasteModeChanged(bool bracketedPasteMode) -{ +void Emulation::bracketedPasteModeChanged(bool bracketedPasteMode) { _bracketedPasteMode = bracketedPasteMode; } -ScreenWindow* Emulation::createWindow() -{ - ScreenWindow* window = new ScreenWindow(); +ScreenWindow *Emulation::createWindow() { + ScreenWindow *window = new ScreenWindow(); window->setScreen(_currentScreen); _windows << window; - connect(window, &ScreenWindow::selectionChanged, - this, &Emulation::bufferedUpdate); - - connect(this, &Emulation::outputChanged, - window, &ScreenWindow::notifyOutputChanged); - - connect(this, &Emulation::handleCommandFromKeyboard, - window, &ScreenWindow::handleCommandFromKeyboard); - connect(this, &Emulation::handleCtrlC, - window, &ScreenWindow::handleCtrlC); - connect(this, &Emulation::outputFromKeypressEvent, - window, &ScreenWindow::scrollToEnd); + connect(window, &ScreenWindow::selectionChanged, this, &Emulation::bufferedUpdate); + connect(this, &Emulation::outputChanged, window, &ScreenWindow::notifyOutputChanged); + connect(this, &Emulation::handleCommandFromKeyboard, window, &ScreenWindow::handleCommandFromKeyboard); + connect(this, &Emulation::handleCtrlC, window, &ScreenWindow::handleCtrlC); + connect(this, &Emulation::outputFromKeypressEvent, window, &ScreenWindow::scrollToEnd); return window; } -void Emulation::checkScreenInUse() -{ +void Emulation::checkScreenInUse() { emit primaryScreenInUse(_currentScreen == _screen[0]); } -Emulation::~Emulation() -{ - QListIterator windowIter(_windows); +Emulation::~Emulation() { + QListIterator windowIter(_windows); - while (windowIter.hasNext()) - { - delete windowIter.next(); - } + while (windowIter.hasNext()) { + delete windowIter.next(); + } - delete _screen[0]; - delete _screen[1]; + delete _screen[0]; + delete _screen[1]; } -void Emulation::setScreen(int n) -{ - Screen *old = _currentScreen; - _currentScreen = _screen[n & 1]; - if (_currentScreen != old) - { - // tell all windows onto this emulation to switch to the newly active screen - for(ScreenWindow* window : std::as_const(_windows)) - window->setScreen(_currentScreen); - checkScreenInUse(); - } +void Emulation::setScreen(int n) { + Screen *old = _currentScreen; + _currentScreen = _screen[n & 1]; + if (_currentScreen != old) { + // tell all windows onto this emulation to switch to the newly active screen + for (ScreenWindow *window : std::as_const(_windows)) + window->setScreen(_currentScreen); + checkScreenInUse(); + } } -void Emulation::clearHistory() -{ - _screen[0]->setScroll( _screen[0]->getScroll() , false ); +void Emulation::clearHistory() { + _screen[0]->setScroll(_screen[0]->getScroll(), false); } -void Emulation::setHistory(const HistoryType& t) -{ - _screen[0]->setScroll(t); - showBulk(); +void Emulation::setHistory(const HistoryType &t) { + _screen[0]->setScroll(t); + + showBulk(); } -const HistoryType& Emulation::history() const -{ - return _screen[0]->getScroll(); +const HistoryType &Emulation::history() const { + return _screen[0]->getScroll(); } -void Emulation::setCodec(QStringEncoder qtc) -{ - if (qtc.isValid()) - _fromUtf16 = std::move(qtc); - else - setCodec(LocaleCodec); +void Emulation::setCodec(QStringEncoder qtc) { + if (qtc.isValid()) + _fromUtf16 = std::move(qtc); + else + setCodec(LocaleCodec); - _toUtf16 = QStringDecoder{utf8() ? QStringConverter::Encoding::Utf8 : QStringConverter::Encoding::System}; - emit useUtf8Request(utf8()); + _toUtf16 = QStringDecoder{utf8() ? QStringConverter::Encoding::Utf8 + : QStringConverter::Encoding::System}; + emit useUtf8Request(utf8()); } -bool Emulation::utf8() const -{ - const auto enc = QStringConverter::encodingForName(_fromUtf16.name()); - return enc && enc.value() == QStringConverter::Encoding::Utf8; +bool Emulation::utf8() const { + const auto enc = QStringConverter::encodingForName(_fromUtf16.name()); + return enc && enc.value() == QStringConverter::Encoding::Utf8; } -void Emulation::setCodec(EmulationCodec codec) -{ - setCodec( QStringEncoder{codec == Utf8Codec ? - QStringConverter::Encoding::Utf8 : - QStringConverter::Encoding::System} ); +void Emulation::setCodec(EmulationCodec codec) { + setCodec(QStringEncoder{codec == Utf8Codec + ? QStringConverter::Encoding::Utf8 + : QStringConverter::Encoding::System}); } -void Emulation::setKeyBindings(const QString& name) -{ - _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); - if (!_keyTranslator) - { - _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator(); - } +void Emulation::setKeyBindings(const QString &name) { + _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); + if (!_keyTranslator) { + _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator(); + } } -QString Emulation::keyBindings() const -{ - return _keyTranslator->name(); +QString Emulation::keyBindings() const { + return _keyTranslator->name(); } -void Emulation::receiveChar(wchar_t c) // process application unicode input to terminal // this is a trivial scanner -{ - c &= 0xff; - switch (c) - { - case '\b' : _currentScreen->backspace(); break; - case '\t' : _currentScreen->tab(); break; - case '\n' : _currentScreen->newLine(); break; - case '\r' : _currentScreen->toStartOfLine(); break; - case 0x07 : emit stateSet(NOTIFYBELL); - break; - default : _currentScreen->displayCharacter(c); break; - }; -} - -void Emulation::sendKeyEvent(QKeyEvent* ev, bool) -{ - emit stateSet(NOTIFYNORMAL); - - if (!ev->text().isEmpty()) - { // A block of text - // Note that the text is proper unicode. - // We should do a conversion here - emit sendData(ev->text().toUtf8().constData(),ev->text().length()); - } -} - -void Emulation::sendString(const char*,int) -{ +void Emulation::receiveChar(wchar_t c) { + c &= 0xff; + switch (c) { + case '\b': + _currentScreen->backspace(); + break; + case '\t': + _currentScreen->tab(); + break; + case '\n': + _currentScreen->newLine(); + break; + case '\r': + _currentScreen->toStartOfLine(); + break; + case 0x07: + emit stateSet(NOTIFYBELL); + break; + default: + _currentScreen->displayCharacter(c); + break; + }; +} + +void Emulation::sendKeyEvent(QKeyEvent *ev, bool) { + emit stateSet(NOTIFYNORMAL); + + if (!ev->text().isEmpty()) { // A block of text + // Note that the text is proper unicode. + // We should do a conversion here + emit sendData(ev->text().toUtf8().constData(), ev->text().length()); + } +} + +void Emulation::sendString(const char *, int) { // default implementation does nothing } -void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int /*eventType*/) -{ +void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, + int /*eventType*/) { // default implementation does nothing } @@ -236,132 +219,73 @@ void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int We are doing code conversion from locale to unicode first. TODO: Character composition from the old code. See #96536 */ - -void Emulation::receiveData(const char* text, int length) -{ +void Emulation::receiveData(const char *text, int length) { emit stateSet(NOTIFYACTIVITY); bufferedUpdate(); /* XXX: the following code involves encoding & decoding of "UTF-16 - * surrogate pairs", which does not work with characters higher than - * U+10FFFF - * https://unicodebook.readthedocs.io/unicode_encodings.html#surrogates - */ + * surrogate pairs", which does not work with characters higher than + * U+10FFFF + * https://unicodebook.readthedocs.io/unicode_encodings.html#surrogates + */ QString utf16Text = _toUtf16(QByteArray::fromRawData(text, length)); std::wstring unicodeText = utf16Text.toStdWString(); - //send characters to terminal emulator + // send characters to terminal emulator for (wchar_t i : unicodeText) receiveChar(i); - //look for z-modem indicator + // look for z-modem indicator //-- someone who understands more about z-modems that I do may be able to move - //this check into the above for loop? - for (int i=0;i 3) && (strncmp(text+i+1, "B00", 3) == 0)) { + if ((length - i - 1 > 3) && (strncmp(text + i + 1, "B00", 3) == 0)) { emit zmodemSendDetected(); } // ZRINIT 1 Receive init - if ((length-i-1 > 5) && (strncmp(text+i+1, "B0100", 5) == 0)) { + if ((length - i - 1 > 5) && (strncmp(text + i + 1, "B0100", 5) == 0)) { emit zmodemRecvDetected(); } } } } - -void Emulation::dupDisplayCharacter(wchar_t cc) -{ - if(cc == L'\n') { + +void Emulation::dupDisplayCharacter(wchar_t cc) { + if (cc == L'\n') { dupCache.append(L'\n'); PlainTextDecoder decoder; QString lineText; QTextStream stream(&lineText); decoder.begin(&stream); Character *data = new Character[dupCache.size()]; - for(int j=0;jtoUnicode(&s[i],1); - int reslen = result.length(); - - // If we get a control code halfway a multi-byte sequence - // we flush the _decoder and continue with the control code. - if ((s[i] < 32) && (s[i] > 0)) - { - // Flush _decoder - while(!result.length()) - result = _decoder->toUnicode(&s[i],1); - reslen = 1; - result.resize(reslen); - result[0] = QChar(s[i]); - } - - for (int j = 0; j < reslen; j++) - { - if (result[j].characterategory() == QChar::Mark_NonSpacing) - _currentScreen->compose(result.mid(j,1)); - else - onRcvChar(result[j].unicode()); - } - if (s[i] == '\030') - { - if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) - emit zmodemSendDetected(); - if ((length-i-1 > 5) && (strncmp(text+i+1, "B0100", 5) == 0)) - emit zmodemRecvDetected(); - } - } -}*/ - -void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , - int startLine , - int endLine) -{ - _currentScreen->writeLinesToStream(_decoder,startLine,endLine); +void Emulation::writeToStream(TerminalCharacterDecoder *_decoder, int startLine, + int endLine) { + _currentScreen->writeLinesToStream(_decoder, startLine, endLine); } -int Emulation::lineCount() const -{ +int Emulation::lineCount() const { // sum number of lines currently on _screen plus number of lines in history return _currentScreen->getLines() + _currentScreen->getHistLines(); } -void Emulation::showBulk() -{ +void Emulation::showBulk() { _bulkTimer1.stop(); _bulkTimer2.stop(); @@ -371,140 +295,123 @@ void Emulation::showBulk() _currentScreen->resetDroppedLines(); } -void Emulation::bufferedUpdate() -{ +void Emulation::bufferedUpdate() { static const int BULK_TIMEOUT1 = 10; static const int BULK_TIMEOUT2 = 40; _bulkTimer1.setSingleShot(true); _bulkTimer1.start(BULK_TIMEOUT1); - if (!_bulkTimer2.isActive()) - { + if (!_bulkTimer2.isActive()) { _bulkTimer2.setSingleShot(true); _bulkTimer2.start(BULK_TIMEOUT2); } } -char Emulation::eraseChar() const -{ - return '\b'; +char Emulation::eraseChar() const { + return '\b'; } -void Emulation::setImageSize(int lines, int columns) -{ - if ((lines < 1) || (columns < 1)) - return; +void Emulation::setImageSize(int lines, int columns) { + if ((lines < 1) || (columns < 1)) + return; - QSize screenSize[2] = { QSize(_screen[0]->getColumns(), - _screen[0]->getLines()), - QSize(_screen[1]->getColumns(), - _screen[1]->getLines()) }; - QSize newSize(columns,lines); + QSize screenSize[2] = { + QSize(_screen[0]->getColumns(), _screen[0]->getLines()), + QSize(_screen[1]->getColumns(), _screen[1]->getLines())}; + QSize newSize(columns, lines); - if (newSize == screenSize[0] && newSize == screenSize[1]) - return; + if (newSize == screenSize[0] && newSize == screenSize[1]) + return; - _screen[0]->resizeImage(lines,columns); - _screen[1]->resizeImage(lines,columns); + _screen[0]->resizeImage(lines, columns); + _screen[1]->resizeImage(lines, columns); - emit imageSizeChanged(lines,columns); + emit imageSizeChanged(lines, columns); - bufferedUpdate(); + bufferedUpdate(); } -QSize Emulation::imageSize() const -{ - return {_currentScreen->getColumns(), _currentScreen->getLines()}; +QSize Emulation::imageSize() const { + return {_currentScreen->getColumns(), _currentScreen->getLines()}; } -ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const -{ +ushort ExtendedCharTable::extendedCharHash(ushort *unicodePoints, + ushort length) const { ushort hash = 0; - for ( ushort i = 0 ; i < length ; i++ ) - { - hash = 31*hash + unicodePoints[i]; + for (ushort i = 0; i < length; i++) { + hash = 31 * hash + unicodePoints[i]; } return hash; } -bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const -{ - ushort* entry = extendedCharTable[hash]; - - // compare given length with stored sequence length ( given as the first ushort in the - // stored buffer ) - if ( entry == nullptr || entry[0] != length ) - return false; - // if the lengths match, each character must be checked. the stored buffer starts at - // entry[1] - for ( int i = 0 ; i < length ; i++ ) - { - if ( entry[i+1] != unicodePoints[i] ) - return false; + +bool ExtendedCharTable::extendedCharMatch(ushort hash, ushort *unicodePoints, + ushort length) const { + ushort *entry = extendedCharTable[hash]; + + // compare given length with stored sequence length ( given as the first + // ushort in the stored buffer ) + if (entry == nullptr || entry[0] != length) + return false; + // if the lengths match, each character must be checked. the stored buffer + // starts at entry[1] + for (int i = 0; i < length; i++) { + if (entry[i + 1] != unicodePoints[i]) + return false; } return true; } -ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) -{ + +ushort ExtendedCharTable::createExtendedChar(ushort *unicodePoints, + ushort length) { // look for this sequence of points in the table - ushort hash = extendedCharHash(unicodePoints,length); + ushort hash = extendedCharHash(unicodePoints, length); // check existing entry for match - while ( extendedCharTable.contains(hash) ) - { - if ( extendedCharMatch(hash,unicodePoints,length) ) - { + while (extendedCharTable.contains(hash)) { + if (extendedCharMatch(hash, unicodePoints, length)) { // this sequence already has an entry in the table, // return its hash return hash; - } - else - { - // if hash is already used by another, different sequence of unicode character - // points then try next hash + } else { + // if hash is already used by another, different sequence of unicode + // character points then try next hash hash++; } } - - // add the new sequence to the table and - // return that index - ushort* buffer = new ushort[length+1]; + // add the new sequence to the table and + // return that index + ushort *buffer = new ushort[length + 1]; buffer[0] = length; - for ( int i = 0 ; i < length ; i++ ) - buffer[i+1] = unicodePoints[i]; + for (int i = 0; i < length; i++) + buffer[i + 1] = unicodePoints[i]; - extendedCharTable.insert(hash,buffer); + extendedCharTable.insert(hash, buffer); return hash; } -ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) const -{ +ushort *ExtendedCharTable::lookupExtendedChar(ushort hash, + ushort &length) const { // lookup index in table and if found, set the length // argument and return a pointer to the character sequence - - ushort* buffer = extendedCharTable[hash]; - if ( buffer ) - { + ushort *buffer = extendedCharTable[hash]; + if (buffer) { length = buffer[0]; - return buffer+1; - } - else - { + return buffer + 1; + } else { length = 0; return nullptr; } } -ExtendedCharTable::ExtendedCharTable() -{ +ExtendedCharTable::ExtendedCharTable() { } -ExtendedCharTable::~ExtendedCharTable() -{ + +ExtendedCharTable::~ExtendedCharTable() { // free all allocated character buffers - QHashIterator iter(extendedCharTable); - while ( iter.hasNext() ) - { + QHashIterator iter(extendedCharTable); + while (iter.hasNext()) { iter.next(); delete[] iter.value(); } @@ -512,5 +419,3 @@ ExtendedCharTable::~ExtendedCharTable() // global instance ExtendedCharTable ExtendedCharTable::instance; - - diff --git a/lib/qtermwidget/Emulation.h b/lib/qtermwidget/Emulation.h index 0caea434..9cb3e6bb 100644 --- a/lib/qtermwidget/Emulation.h +++ b/lib/qtermwidget/Emulation.h @@ -1,23 +1,23 @@ /* - This file is part of Konsole, an X terminal. - - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef EMULATION_H #define EMULATION_H @@ -116,413 +116,411 @@ class Emulation : public QObject Q_OBJECT public: - /** - * This enum describes the available shapes for the keyboard cursor. - * See setKeyboardCursorShape() - */ - enum class KeyboardCursorShape { - /** A rectangular block which covers the entire area of the cursor character. */ - BlockCursor = 0, - /** - * A single flat line which occupies the space at the bottom of the cursor - * character's area. - */ - UnderlineCursor = 1, - /** - * An cursor shaped like the capital letter 'I', similar to the IBeam - * cursor used in Qt/KDE text editors. - */ - IBeamCursor = 2 - }; - - - /** Constructs a new terminal emulation */ - Emulation(); - ~Emulation() override; - - /** - * Creates a new window onto the output from this emulation. The contents - * of the window are then rendered by views which are set to use this window using the - * TerminalDisplay::setScreenWindow() method. - */ - ScreenWindow* createWindow(); - - /** Returns the size of the screen image which the emulation produces */ - QSize imageSize() const; - - /** - * Returns the total number of lines, including those stored in the history. - */ - int lineCount() const; - - /** - * Sets the history store used by this emulation. When new lines - * are added to the output, older lines at the top of the screen are transferred to a history - * store. - * - * The number of lines which are kept and the storage location depend on the - * type of store. - */ - void setHistory(const HistoryType&); - /** Returns the history store used by this emulation. See setHistory() */ - const HistoryType& history() const; - /** Clears the history scroll. */ - void clearHistory(); - - /** - * Copies the output history from @p startLine to @p endLine - * into @p stream, using @p decoder to convert the terminal - * characters into text. - * - * @param decoder A decoder which converts lines of terminal characters with - * appearance attributes into output text. PlainTextDecoder is the most commonly - * used decoder. - * @param startLine Index of first line to copy - * @param endLine Index of last line to copy - */ - virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); - - /** Returns the codec used to decode incoming characters. See setCodec() */ - const QStringEncoder &codec() const { return _fromUtf16; } - /** Sets the codec used to decode incoming characters. */ - void setCodec(QStringEncoder); - - /** - * Convenience method. - * Returns true if the current codec used to decode incoming - * characters is UTF-8 - */ - bool utf8() const; - - /** TODO Document me */ - virtual char eraseChar() const; - - /** - * Sets the key bindings used to key events - * ( received through sendKeyEvent() ) into character - * streams to send to the terminal. - */ - void setKeyBindings(const QString& name); - /** - * Returns the name of the emulation's current key bindings. - * See setKeyBindings() - */ - QString keyBindings() const; - - /** - * Copies the current image into the history and clears the screen. - */ - virtual void clearEntireScreen() =0; - - /** Resets the state of the terminal. */ - virtual void reset() =0; - - /** - * Returns true if the active terminal program wants - * mouse input events. - * - * The programUsesMouseChanged() signal is emitted when this - * changes. - */ - bool programUsesMouse() const; - - bool programBracketedPasteMode() const; - - void setEnableHandleCtrlC(bool enable) { _enableHandleCtrlC = enable; } + /** + * This enum describes the available shapes for the keyboard cursor. + * See setKeyboardCursorShape() + */ + enum class KeyboardCursorShape { + /** A rectangular block which covers the entire area of the cursor character. */ + BlockCursor = 0, + /** + * A single flat line which occupies the space at the bottom of the cursor + * character's area. + */ + UnderlineCursor = 1, + /** + * An cursor shaped like the capital letter 'I', similar to the IBeam + * cursor used in Qt/KDE text editors. + */ + IBeamCursor = 2 + }; + + + /** Constructs a new terminal emulation */ + Emulation(); + ~Emulation() override; + + /** + * Creates a new window onto the output from this emulation. The contents + * of the window are then rendered by views which are set to use this window using the + * TerminalDisplay::setScreenWindow() method. + */ + ScreenWindow* createWindow(); + + /** Returns the size of the screen image which the emulation produces */ + QSize imageSize() const; + + /** + * Returns the total number of lines, including those stored in the history. + */ + int lineCount() const; + + /** + * Sets the history store used by this emulation. When new lines + * are added to the output, older lines at the top of the screen are transferred to a history + * store. + * + * The number of lines which are kept and the storage location depend on the + * type of store. + */ + void setHistory(const HistoryType&); + /** Returns the history store used by this emulation. See setHistory() */ + const HistoryType& history() const; + /** Clears the history scroll. */ + void clearHistory(); + + /** + * Copies the output history from @p startLine to @p endLine + * into @p stream, using @p decoder to convert the terminal + * characters into text. + * + * @param decoder A decoder which converts lines of terminal characters with + * appearance attributes into output text. PlainTextDecoder is the most commonly + * used decoder. + * @param startLine Index of first line to copy + * @param endLine Index of last line to copy + */ + virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); + + /** Returns the codec used to decode incoming characters. See setCodec() */ + const QStringEncoder &codec() const { return _fromUtf16; } + /** Sets the codec used to decode incoming characters. */ + void setCodec(QStringEncoder); + + /** + * Convenience method. + * Returns true if the current codec used to decode incoming + * characters is UTF-8 + */ + bool utf8() const; + + /** TODO Document me */ + virtual char eraseChar() const; + + /** + * Sets the key bindings used to key events + * ( received through sendKeyEvent() ) into character + * streams to send to the terminal. + */ + void setKeyBindings(const QString& name); + /** + * Returns the name of the emulation's current key bindings. + * See setKeyBindings() + */ + QString keyBindings() const; + + /** + * Copies the current image into the history and clears the screen. + */ + virtual void clearEntireScreen() =0; + + /** Resets the state of the terminal. */ + virtual void reset() =0; + + /** + * Returns true if the active terminal program wants + * mouse input events. + * + * The programUsesMouseChanged() signal is emitted when this + * changes. + */ + bool programUsesMouse() const; + + bool programBracketedPasteMode() const; + + void setEnableHandleCtrlC(bool enable) { _enableHandleCtrlC = enable; } public slots: - /** Change the size of the emulation's image */ - virtual void setImageSize(int lines, int columns); - - /** - * Interprets a sequence of characters and sends the result to the terminal. - * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. - */ - virtual void sendText(const QString& text) = 0; - - /** - * Interprets a key press event and emits the sendData() signal with - * the resulting character stream. - */ - virtual void sendKeyEvent(QKeyEvent*, bool fromPaste); - - /** - * Converts information about a mouse event into an xterm-compatible escape - * sequence and emits the character sequence via sendData() - */ - virtual void sendMouseEvent(int buttons, int column, int line, int eventType); - - /** - * Sends a string of characters to the foreground terminal process. - * - * @param string The characters to send. - * @param length Length of @p string or if set to a negative value, @p string will - * be treated as a null-terminated string and its length will be determined automatically. - */ - virtual void sendString(const char* string, int length = -1) = 0; - - /** - * Processes an incoming stream of characters. receiveData() decodes the incoming - * character buffer using the current codec(), and then calls receiveChar() for - * each unicode character in the resulting buffer. - * - * receiveData() also starts a timer which causes the outputChanged() signal - * to be emitted when it expires. The timer allows multiple updates in quick - * succession to be buffered into a single outputChanged() signal emission. - * - * @param buffer A string of characters received from the terminal program. - * @param len The length of @p buffer - */ - void receiveData(const char* buffer,int len); - - void dupDisplayCharacter(wchar_t cc); + /** Change the size of the emulation's image */ + virtual void setImageSize(int lines, int columns); + + /** + * Interprets a sequence of characters and sends the result to the terminal. + * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. + */ + virtual void sendText(const QString& text) = 0; + + /** + * Interprets a key press event and emits the sendData() signal with + * the resulting character stream. + */ + virtual void sendKeyEvent(QKeyEvent*, bool fromPaste); + + /** + * Converts information about a mouse event into an xterm-compatible escape + * sequence and emits the character sequence via sendData() + */ + virtual void sendMouseEvent(int buttons, int column, int line, int eventType); + + /** + * Sends a string of characters to the foreground terminal process. + * + * @param string The characters to send. + * @param length Length of @p string or if set to a negative value, @p string will + * be treated as a null-terminated string and its length will be determined automatically. + */ + virtual void sendString(const char* string, int length = -1) = 0; + + /** + * Processes an incoming stream of characters. receiveData() decodes the incoming + * character buffer using the current codec(), and then calls receiveChar() for + * each unicode character in the resulting buffer. + * + * receiveData() also starts a timer which causes the outputChanged() signal + * to be emitted when it expires. The timer allows multiple updates in quick + * succession to be buffered into a single outputChanged() signal emission. + * + * @param buffer A string of characters received from the terminal program. + * @param len The length of @p buffer + */ + void receiveData(const char* buffer,int len); + + void dupDisplayCharacter(wchar_t cc); signals: - /** - * Emitted when a buffer of data is ready to send to the - * standard input of the terminal. - * - * @param data The buffer of data ready to be sent - * @param len The length of @p data in bytes - */ - void sendData(const char* data,int len); - - void dupDisplayOutput(const char* data,int len); - - /** - * Requests that sending of input to the emulation - * from the terminal process be suspended or resumed. - * - * @param suspend If true, requests that sending of - * input from the terminal process' stdout be - * suspended. Otherwise requests that sending of - * input be resumed. - */ - void lockPtyRequest(bool suspend); - - /** - * Requests that the pty used by the terminal process - * be set to UTF 8 mode. - * - * TODO: More documentation - */ - void useUtf8Request(bool); - - /** - * Emitted when the activity state of the emulation is set. - * - * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY - * or NOTIFYBELL - */ - void stateSet(int state); - - /** ZModem file transfer detected */ - void zmodemSendDetected(); - void zmodemRecvDetected(); - - - /** - * Requests that the color of the text used - * to represent the tabs associated with this - * emulation be changed. This is a Konsole-specific - * extension from pre-KDE 4 times. - * - * TODO: Document how the parameter works. - */ - void changeTabTextColorRequest(int color); - - /** - * This is emitted when the program running in the shell indicates whether or - * not it is interested in mouse events. - * - * @param usesMouse This will be true if the program wants to be informed about - * mouse events or false otherwise. - */ - void programUsesMouseChanged(bool usesMouse); - - void programBracketedPasteModeChanged(bool bracketedPasteMode); - - /** - * Emitted when the contents of the screen image change. - * The emulation buffers the updates from successive image changes, - * and only emits outputChanged() at sensible intervals when - * there is a lot of terminal activity. - * - * Normally there is no need for objects other than the screen windows - * created with createWindow() to listen for this signal. - * - * ScreenWindow objects created using createWindow() will emit their - * own outputChanged() signal in response to this signal. - */ - void outputChanged(); - - /** - * Emitted when the program running in the terminal wishes to update the - * session's title. This also allows terminal programs to customize other - * aspects of the terminal emulation display. - * - * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" - * is received in the input string, where ARG is a number specifying what - * should change and VALUE is a string specifying the new value. - * - * TODO: The name of this method is not very accurate since this method - * is used to perform a whole range of tasks besides just setting - * the user-title of the session. - * - * @param title Specifies what to change. - *
    - *
  • 0 - Set window icon text and session title to @p newTitle
  • - *
  • 1 - Set window icon text to @p newTitle
  • - *
  • 2 - Set session title to @p newTitle
  • - *
  • 11 - Set the session's default background color to @p newTitle, - * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named - * color (eg 'red', 'blue'). - * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more - * details. - *
  • - *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • - *
  • 32 - Sets the icon associated with the session. @p newTitle is the name - * of the icon to use, which can be the name of any icon in the current KDE icon - * theme (eg: 'konsole', 'kate', 'folder_home')
  • - *
- * @param newTitle Specifies the new title - */ - - void titleChanged(int title,const QString& newTitle); - - /** - * Emitted when the program running in the terminal changes the - * screen size. - */ - void imageSizeChanged(int lineCount , int columnCount); - - /** - * Emitted when the setImageSize() is called on this emulation for - * the first time. - */ - void imageSizeInitialized(); - - /** - * Emitted after receiving the escape sequence which asks to change - * the terminal emulator's size - */ - void imageResizeRequest(const QSize& size); - - /** - * Emitted when the terminal program requests to change various properties - * of the terminal display. - * - * A profile change command occurs when a special escape sequence, followed - * by a string containing a series of name and value pairs is received. - * This string can be parsed using a ProfileCommandParser instance. - * - * @param text A string expected to contain a series of key and value pairs in - * the form: name=value;name2=value2 ... - */ - void profileChangeCommandReceived(const QString& text); - - /** - * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. - * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to - * resume output. - */ - void flowControlKeyPressed(bool suspendKeyPressed); - - /** - * Emitted when the active screen is switched, to indicate whether the primary - * screen is in use. - */ - void primaryScreenInUse(bool use); - - /** - * Emitted when the cursor shape or its blinking state is changed via - * DECSCUSR sequences. - * - * @param cursorShape One of 3 possible values in KeyboardCursorShape enum - * @param blinkingCursorEnabled Whether to enable blinking or not - */ - void cursorChanged(KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); - - void handleCommandFromKeyboard(KeyboardTranslator::Command command); - void handleCtrlC(void); - void outputFromKeypressEvent(void); + /** + * Emitted when a buffer of data is ready to send to the + * standard input of the terminal. + * + * @param data The buffer of data ready to be sent + * @param len The length of @p data in bytes + */ + void sendData(const char* data,int len); + + void dupDisplayOutput(const char* data,int len); + + /** + * Requests that sending of input to the emulation + * from the terminal process be suspended or resumed. + * + * @param suspend If true, requests that sending of + * input from the terminal process' stdout be + * suspended. Otherwise requests that sending of + * input be resumed. + */ + void lockPtyRequest(bool suspend); + + /** + * Requests that the pty used by the terminal process + * be set to UTF 8 mode. + * + * TODO: More documentation + */ + void useUtf8Request(bool); + + /** + * Emitted when the activity state of the emulation is set. + * + * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY + * or NOTIFYBELL + */ + void stateSet(int state); + + /** ZModem file transfer detected */ + void zmodemSendDetected(); + void zmodemRecvDetected(); + + + /** + * Requests that the color of the text used + * to represent the tabs associated with this + * emulation be changed. This is a Konsole-specific + * extension from pre-KDE 4 times. + * + * TODO: Document how the parameter works. + */ + void changeTabTextColorRequest(int color); + + /** + * This is emitted when the program running in the shell indicates whether or + * not it is interested in mouse events. + * + * @param usesMouse This will be true if the program wants to be informed about + * mouse events or false otherwise. + */ + void programUsesMouseChanged(bool usesMouse); + + void programBracketedPasteModeChanged(bool bracketedPasteMode); + + /** + * Emitted when the contents of the screen image change. + * The emulation buffers the updates from successive image changes, + * and only emits outputChanged() at sensible intervals when + * there is a lot of terminal activity. + * + * Normally there is no need for objects other than the screen windows + * created with createWindow() to listen for this signal. + * + * ScreenWindow objects created using createWindow() will emit their + * own outputChanged() signal in response to this signal. + */ + void outputChanged(); + + /** + * Emitted when the program running in the terminal wishes to update the + * session's title. This also allows terminal programs to customize other + * aspects of the terminal emulation display. + * + * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" + * is received in the input string, where ARG is a number specifying what + * should change and VALUE is a string specifying the new value. + * + * TODO: The name of this method is not very accurate since this method + * is used to perform a whole range of tasks besides just setting + * the user-title of the session. + * + * @param title Specifies what to change. + *
    + *
  • 0 - Set window icon text and session title to @p newTitle
  • + *
  • 1 - Set window icon text to @p newTitle
  • + *
  • 2 - Set session title to @p newTitle
  • + *
  • 11 - Set the session's default background color to @p newTitle, + * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named + * color (eg 'red', 'blue'). + * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more + * details. + *
  • + *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • + *
  • 32 - Sets the icon associated with the session. @p newTitle is the name + * of the icon to use, which can be the name of any icon in the current KDE icon + * theme (eg: 'konsole', 'kate', 'folder_home')
  • + *
+ * @param newTitle Specifies the new title + */ + + void titleChanged(int title,const QString& newTitle); + + /** + * Emitted when the program running in the terminal changes the + * screen size. + */ + void imageSizeChanged(int lineCount , int columnCount); + + /** + * Emitted when the setImageSize() is called on this emulation for + * the first time. + */ + void imageSizeInitialized(); + + /** + * Emitted after receiving the escape sequence which asks to change + * the terminal emulator's size + */ + void imageResizeRequest(const QSize& size); + + /** + * Emitted when the terminal program requests to change various properties + * of the terminal display. + * + * A profile change command occurs when a special escape sequence, followed + * by a string containing a series of name and value pairs is received. + * This string can be parsed using a ProfileCommandParser instance. + * + * @param text A string expected to contain a series of key and value pairs in + * the form: name=value;name2=value2 ... + */ + void profileChangeCommandReceived(const QString& text); + + /** + * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. + * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to + * resume output. + */ + void flowControlKeyPressed(bool suspendKeyPressed); + + /** + * Emitted when the active screen is switched, to indicate whether the primary + * screen is in use. + */ + void primaryScreenInUse(bool use); + + /** + * Emitted when the cursor shape or its blinking state is changed via + * DECSCUSR sequences. + * + * @param cursorShape One of 3 possible values in KeyboardCursorShape enum + * @param blinkingCursorEnabled Whether to enable blinking or not + */ + void cursorChanged(KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); + + void handleCommandFromKeyboard(KeyboardTranslator::Command command); + void handleCtrlC(void); + void outputFromKeypressEvent(void); protected: - virtual void setMode(int mode) = 0; - virtual void resetMode(int mode) = 0; - - /** - * Processes an incoming character. See receiveData() - * @p ch A unicode character code. - */ - virtual void receiveChar(wchar_t ch); - - /** - * Sets the active screen. The terminal has two screens, primary and alternate. - * The primary screen is used by default. When certain interactive programs such - * as Vim are run, they trigger a switch to the alternate screen. - * - * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen - */ - void setScreen(int index); - - enum EmulationCodec - { - LocaleCodec = 0, - Utf8Codec = 1 - }; - void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8 - - - QList _windows; - - Screen* _currentScreen; // pointer to the screen which is currently active, - // this is one of the elements in the screen[] array - - Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell - // scrollbars are enabled in this mode ) - // 1 = alternate ( used by vi , emacs etc. - // scrollbars are not enabled in this mode ) - - //decodes an incoming C-style character stream into a unicode QString using - //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) - QStringEncoder _fromUtf16; - QStringDecoder _toUtf16; - - const KeyboardTranslator* _keyTranslator; // the keyboard layout - - bool _enableHandleCtrlC; + virtual void setMode(int mode) = 0; + virtual void resetMode(int mode) = 0; + + /** + * Processes an incoming character. See receiveData() + * @p ch A unicode character code. + */ + virtual void receiveChar(wchar_t ch); + + /** + * Sets the active screen. The terminal has two screens, primary and alternate. + * The primary screen is used by default. When certain interactive programs such + * as Vim are run, they trigger a switch to the alternate screen. + * + * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen + */ + void setScreen(int index); + + enum EmulationCodec { + LocaleCodec = 0, + Utf8Codec = 1 + }; + void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8 + + QList _windows; + + Screen* _currentScreen; // pointer to the screen which is currently active, + // this is one of the elements in the screen[] array + + Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell + // scrollbars are enabled in this mode ) + // 1 = alternate ( used by vi , emacs etc. + // scrollbars are not enabled in this mode ) + + //decodes an incoming C-style character stream into a unicode QString using + //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) + QStringEncoder _fromUtf16; + QStringDecoder _toUtf16; + + const KeyboardTranslator* _keyTranslator; // the keyboard layout + + bool _enableHandleCtrlC; protected slots: - /** - * Schedules an update of attached views. - * Repeated calls to bufferedUpdate() in close succession will result in only a single update, - * much like the Qt buffered update of widgets. - */ - void bufferedUpdate(); - - // used to emit the primaryScreenInUse(bool) signal - void checkScreenInUse(); + /** + * Schedules an update of attached views. + * Repeated calls to bufferedUpdate() in close succession will result in only a single update, + * much like the Qt buffered update of widgets. + */ + void bufferedUpdate(); + + // used to emit the primaryScreenInUse(bool) signal + void checkScreenInUse(); private slots: - // triggered by timer, causes the emulation to send an updated screen image to each - // view - void showBulk(); + // triggered by timer, causes the emulation to send an updated screen image to each + // view + void showBulk(); - void usesMouseChanged(bool usesMouse); + void usesMouseChanged(bool usesMouse); - void bracketedPasteModeChanged(bool bracketedPasteMode); + void bracketedPasteModeChanged(bool bracketedPasteMode); private: - bool _usesMouse; - bool _bracketedPasteMode; - QTimer _bulkTimer1{this}; - QTimer _bulkTimer2{this}; - QStringEncoder _fromUtf8; - QByteArray dupCache; + bool _usesMouse; + bool _bracketedPasteMode; + QTimer _bulkTimer1{this}; + QTimer _bulkTimer2{this}; + QStringEncoder _fromUtf8; + QByteArray dupCache; }; -#endif // ifndef EMULATION_H +#endif // EMULATION_H diff --git a/lib/qtermwidget/ExtendedDefaultTranslator.h b/lib/qtermwidget/ExtendedDefaultTranslator.h deleted file mode 100644 index 6403c729..00000000 --- a/lib/qtermwidget/ExtendedDefaultTranslator.h +++ /dev/null @@ -1,74 +0,0 @@ -"keyboard \"Default (XFree 4)\"" -"key Escape : \"\\E\"" -"key Tab -Shift : \"\\t\"\n" -"key Tab +Shift+Ansi : \"\\E[Z\"\n" -"key Tab +Shift-Ansi : \"\\t\"\n" -"key Backtab +Ansi : \"\\E[Z\"\n" -"key Backtab -Ansi : \"\\t\"\n" -"key Return-Shift-NewLine : \"\\r\"\n" -"key Return-Shift+NewLine : \"\\r\\n\"\n" -"key Return+Shift : \"\\EOM\"\n" -"key Backspace : \"\\x7f\"\n" -"key Up -Shift-Ansi : \"\\EA\"\n" -"key Down -Shift-Ansi : \"\\EB\"\n" -"key Right-Shift-Ansi : \"\\EC\"\n" -"key Left -Shift-Ansi : \"\\ED\"\n" -"key Up -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOA\"\n" -"key Down -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOB\"\n" -"key Right -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOC\"\n" -"key Left -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOD\"\n" -"key Up -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[A\"\n" -"key Down -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[B\"\n" -"key Right -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[C\"\n" -"key Left -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[D\"\n" -"key Up -Shift+AnyMod+Ansi : \"\\E[1;*A\"\n" -"key Down -Shift+AnyMod+Ansi : \"\\E[1;*B\"\n" -"key Right -Shift+AnyMod+Ansi : \"\\E[1;*C\"\n" -"key Left -Shift+AnyMod+Ansi : \"\\E[1;*D\"\n" -"key Enter+NewLine : \"\\r\\n\"\n" -"key Enter-NewLine : \"\\r\"\n" -"key Home -AnyMod -AppCuKeys : \"\\E[H\" \n" -"key End -AnyMod -AppCuKeys : \"\\E[F\" \n" -"key Home -AnyMod +AppCuKeys : \"\\EOH\" \n" -"key End -AnyMod +AppCuKeys : \"\\EOF\" \n" -"key Home +AnyMod : \"\\E[1;*H\"\n" -"key End +AnyMod : \"\\E[1;*F\"\n" -"key Insert -AnyMod : \"\\E[2~\"\n" -"key Delete -AnyMod : \"\\E[3~\"\n" -"key Insert +AnyMod : \"\\E[2;*~\"\n" -"key Delete +AnyMod : \"\\E[3;*~\"\n" -"key Prior -Shift-AnyMod : \"\\E[5~\"\n" -"key Next -Shift-AnyMod : \"\\E[6~\"\n" -"key Prior -Shift+AnyMod : \"\\E[5;*~\"\n" -"key Next -Shift+AnyMod : \"\\E[6;*~\"\n" -"key F1 -AnyMod : \"\\EOP\"\n" -"key F2 -AnyMod : \"\\EOQ\"\n" -"key F3 -AnyMod : \"\\EOR\"\n" -"key F4 -AnyMod : \"\\EOS\"\n" -"key F5 -AnyMod : \"\\E[15~\"\n" -"key F6 -AnyMod : \"\\E[17~\"\n" -"key F7 -AnyMod : \"\\E[18~\"\n" -"key F8 -AnyMod : \"\\E[19~\"\n" -"key F9 -AnyMod : \"\\E[20~\"\n" -"key F10 -AnyMod : \"\\E[21~\"\n" -"key F11 -AnyMod : \"\\E[23~\"\n" -"key F12 -AnyMod : \"\\E[24~\"\n" -"key F1 +AnyMod : \"\\EO*P\"\n" -"key F2 +AnyMod : \"\\EO*Q\"\n" -"key F3 +AnyMod : \"\\EO*R\"\n" -"key F4 +AnyMod : \"\\EO*S\"\n" -"key F5 +AnyMod : \"\\E[15;*~\"\n" -"key F6 +AnyMod : \"\\E[17;*~\"\n" -"key F7 +AnyMod : \"\\E[18;*~\"\n" -"key F8 +AnyMod : \"\\E[19;*~\"\n" -"key F9 +AnyMod : \"\\E[20;*~\"\n" -"key F10 +AnyMod : \"\\E[21;*~\"\n" -"key F11 +AnyMod : \"\\E[23;*~\"\n" -"key F12 +AnyMod : \"\\E[24;*~\"\n" -"key Space +Control : \"\\x00\"\n" -"key Up +Shift-AppScreen : scrollLineUp\n" -"key Prior +Shift-AppScreen : scrollPageUp\n" -"key Down +Shift-AppScreen : scrollLineDown\n" -"key Next +Shift-AppScreen : scrollPageDown\n" -"key ScrollLock : scrollLock\n" -"\0" diff --git a/lib/qtermwidget/Filter.cpp b/lib/qtermwidget/Filter.cpp index d750d856..087945e1 100644 --- a/lib/qtermwidget/Filter.cpp +++ b/lib/qtermwidget/Filter.cpp @@ -1,125 +1,117 @@ /* - Copyright 2007-2008 by Robert Knight - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2007-2008 by Robert Knight + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ - #include "Filter.h" #include #include #include -#include #include +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include +#include -#include "TerminalCharacterDecoder.h" #include "CharWidth.h" +#include "TerminalCharacterDecoder.h" #include "qtermwidget.h" -FilterChain::~FilterChain() -{ - +FilterChain::~FilterChain() { } -void FilterChain::addFilter(Filter* filter) -{ - if(!containsFilter(filter)) +void FilterChain::addFilter(Filter *filter) { + if (!containsFilter(filter)) append(filter); } -void FilterChain::removeFilter(Filter* filter) -{ - removeAll(filter); + +void FilterChain::removeFilter(Filter *filter) { + removeAll(filter); } -bool FilterChain::containsFilter(Filter* filter) -{ - return contains(filter); + +bool FilterChain::containsFilter(Filter *filter) { + return contains(filter); } -void FilterChain::reset() -{ - QListIterator iter(*this); + +void FilterChain::reset() { + QListIterator iter(*this); while (iter.hasNext()) iter.next()->reset(); } -void FilterChain::setBuffer(const QString* buffer , const QList* linePositions) -{ - QListIterator iter(*this); + +void FilterChain::setBuffer(const QString *buffer, + const QList *linePositions) { + QListIterator iter(*this); while (iter.hasNext()) - iter.next()->setBuffer(buffer,linePositions); + iter.next()->setBuffer(buffer, linePositions); } -void FilterChain::process() -{ - QListIterator iter(*this); + +void FilterChain::process() { + QListIterator iter(*this); while (iter.hasNext()) iter.next()->process(); } -void FilterChain::clear() -{ - QList::clear(); + +void FilterChain::clear() { + QList::clear(); } -Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const -{ - QListIterator iter(*this); - while (iter.hasNext()) - { - Filter* filter = iter.next(); - Filter::HotSpot* spot = filter->hotSpotAt(line,column); - if ( spot != nullptr ) - { - return spot; + +Filter::HotSpot *FilterChain::hotSpotAt(int line, int column) const { + QListIterator iter(*this); + while (iter.hasNext()) { + Filter *filter = iter.next(); + Filter::HotSpot *spot = filter->hotSpotAt(line, column); + if (spot != nullptr) { + return spot; } } return nullptr; } -QList FilterChain::hotSpots() const -{ - QList list; - QListIterator iter(*this); - while (iter.hasNext()) - { - Filter* filter = iter.next(); +QList FilterChain::hotSpots() const { + QList list; + QListIterator iter(*this); + while (iter.hasNext()) { + Filter *filter = iter.next(); list << filter->hotSpots(); } return list; } + //QList FilterChain::hotSpotsAtLine(int line) const; TerminalImageFilterChain::TerminalImageFilterChain() -: _buffer(nullptr) -, _linePositions(nullptr) -{ + : _buffer(nullptr), _linePositions(nullptr) { } -TerminalImageFilterChain::~TerminalImageFilterChain() -{ +TerminalImageFilterChain::~TerminalImageFilterChain() { delete _buffer; delete _linePositions; } -void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector& lineProperties) -{ +void TerminalImageFilterChain::setImage( + const Character *const image, int lines, int columns, + const QVector &lineProperties) { if (empty()) return; @@ -130,9 +122,9 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines decoder.setTrailingWhitespace(false); // setup new shared buffers for the filters to process on - QString* newBuffer = new QString(); - QList* newLinePositions = new QList(); - setBuffer( newBuffer , newLinePositions ); + QString *newBuffer = new QString(); + QList *newLinePositions = new QList(); + setBuffer(newBuffer, newLinePositions); // free the old buffers delete _buffer; @@ -144,117 +136,98 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines QTextStream lineStream(_buffer); decoder.begin(&lineStream); - for (int i=0 ; i < lines ; i++) - { + for (int i = 0; i < lines; i++) { _linePositions->append(_buffer->length()); - decoder.decodeLine(image + i*columns,columns,LINE_DEFAULT); + decoder.decodeLine(image + i * columns, columns, LINE_DEFAULT); // pretend that each line ends with a newline character. // this prevents a link that occurs at the end of one line // being treated as part of a link that occurs at the start of the next line // - // the downside is that links which are spread over more than one line are not - // highlighted. + // the downside is that links which are spread over more than one line are + // not highlighted. // // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped // lines - if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) - lineStream << QLatin1Char('\n'); + if (!(lineProperties.value(i, LINE_DEFAULT) & LINE_WRAPPED)) + lineStream << QLatin1Char('\n'); } decoder.end(); } -Filter::Filter() : QObject(nullptr) -{ +Filter::Filter() : QObject(nullptr) { } -Filter::~Filter() -{ +Filter::~Filter() { qDeleteAll(_hotspotList); _hotspotList.clear(); } -void Filter::reset() -{ +void Filter::reset() { qDeleteAll(_hotspotList); _hotspots.clear(); _hotspotList.clear(); } -void Filter::setBuffer(const QString* buffer , const QList* linePositions) -{ +void Filter::setBuffer(const QString *buffer, const QList *linePositions) { _buffer = buffer; _linePositions = linePositions; } -void Filter::getLineColumn(int position , int& startLine , int& startColumn) -{ - Q_ASSERT( _linePositions ); - Q_ASSERT( _buffer ); +void Filter::getLineColumn(int position, int &startLine, int &startColumn) { + Q_ASSERT(_linePositions); + Q_ASSERT(_buffer); - - for (int i = 0 ; i < _linePositions->count() ; i++) - { + for (int i = 0; i < _linePositions->count(); i++) { int nextLine = 0; - if ( i == _linePositions->count()-1 ) - nextLine = _buffer->length() + 1; + if (i == _linePositions->count() - 1) + nextLine = _buffer->length() + 1; else - nextLine = _linePositions->value(i+1); + nextLine = _linePositions->value(i + 1); - if ( _linePositions->value(i) <= position && position < nextLine ) - { + if (_linePositions->value(i) <= position && position < nextLine) { startLine = i; - startColumn = CharWidth::string_unicode_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(i))); + startColumn = CharWidth::string_unicode_width(buffer()->mid( + _linePositions->value(i), position - _linePositions->value(i))); return; } } } - -/*void Filter::addLine(const QString& text) -{ - _linePositions << _buffer.length(); - _buffer.append(text); -}*/ - -const QString* Filter::buffer() -{ - return _buffer; +const QString *Filter::buffer() { + return _buffer; } -Filter::HotSpot::~HotSpot() -{ + +Filter::HotSpot::~HotSpot() { } -void Filter::addHotSpot(HotSpot* spot) -{ + +void Filter::addHotSpot(HotSpot *spot) { _hotspotList << spot; - for (int line = spot->startLine() ; line <= spot->endLine() ; line++) - { - _hotspots.insert(line,spot); + for (int line = spot->startLine(); line <= spot->endLine(); line++) { + _hotspots.insert(line, spot); } } -QList Filter::hotSpots() const -{ - return _hotspotList; + +QList Filter::hotSpots() const { + return _hotspotList; } -QList Filter::hotSpotsAtLine(int line) const -{ + +QList Filter::hotSpotsAtLine(int line) const { return _hotspots.values(line); } -Filter::HotSpot* Filter::hotSpotAt(int line , int column) const -{ - QListIterator spotIter(_hotspots.values(line)); +Filter::HotSpot *Filter::hotSpotAt(int line, int column) const { + QListIterator spotIter(_hotspots.values(line)); - while (spotIter.hasNext()) - { - HotSpot* spot = spotIter.next(); + while (spotIter.hasNext()) { + HotSpot *spot = spotIter.next(); - if ( spot->startLine() == line && spot->startColumn() > column ) + if (spot->startLine() == line && spot->startColumn() > column) continue; - if ( spot->endLine() == line && spot->endColumn() < column ) + if (spot->endLine() == line && spot->endColumn() < column) continue; return spot; @@ -263,108 +236,53 @@ Filter::HotSpot* Filter::hotSpotAt(int line , int column) const return nullptr; } -Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn) - : _startLine(startLine) - , _startColumn(startColumn) - , _endLine(endLine) - , _endColumn(endColumn) - , _type(NotSpecified) - , _color(Qt::red) -{ -} -QList Filter::HotSpot::actions() -{ - return QList(); -} -int Filter::HotSpot::startLine() const -{ - return _startLine; -} -int Filter::HotSpot::endLine() const -{ - return _endLine; -} -int Filter::HotSpot::startColumn() const -{ - return _startColumn; -} -int Filter::HotSpot::endColumn() const -{ - return _endColumn; -} -Filter::HotSpot::Type Filter::HotSpot::type() const -{ - return _type; -} -QColor Filter::HotSpot::color() const -{ - return _color; -} -void Filter::HotSpot::setType(Type type) -{ - _type = type; -} -void Filter::HotSpot::setColor(const QColor& color) -{ - _color = color; -} +Filter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) + : _startLine(startLine), _startColumn(startColumn), _endLine(endLine), + _endColumn(endColumn), _type(NotSpecified), _color(Qt::red) {} +QList Filter::HotSpot::actions() { return QList(); } +int Filter::HotSpot::startLine() const { return _startLine; } +int Filter::HotSpot::endLine() const { return _endLine; } +int Filter::HotSpot::startColumn() const { return _startColumn; } +int Filter::HotSpot::endColumn() const { return _endColumn; } +Filter::HotSpot::Type Filter::HotSpot::type() const { return _type; } +QColor Filter::HotSpot::color() const { return _color; } +void Filter::HotSpot::setType(Type type) { _type = type; } +void Filter::HotSpot::setColor(const QColor &color) { _color = color; } -RegExpFilter::RegExpFilter() : Filter() -{ +RegExpFilter::RegExpFilter() : Filter() { } -RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) - : Filter::HotSpot(startLine,startColumn,endLine,endColumn) -{ +RegExpFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, + int endColumn) + : Filter::HotSpot(startLine, startColumn, endLine, endColumn) { setType(Marker); } -void RegExpFilter::HotSpot::clickAction(void) -{ +void RegExpFilter::HotSpot::clickAction(void) {} +QString RegExpFilter::HotSpot::clickActionToolTip(void) { return QString(); } +bool RegExpFilter::HotSpot::hasClickAction(void) { return false; } +void RegExpFilter::HotSpot::setCapturedTexts(const QStringList &texts) { + _capturedTexts = texts; } - -QString RegExpFilter::HotSpot::clickActionToolTip(void) -{ - return QString(); +QStringList RegExpFilter::HotSpot::capturedTexts() const { + return _capturedTexts; } - -bool RegExpFilter::HotSpot::hasClickAction(void) -{ - return false; +void RegExpFilter::setRegExp(const QRegularExpression ®Exp) { + _searchText = regExp; } +QRegularExpression RegExpFilter::regExp() const { return _searchText; } -void RegExpFilter::HotSpot::setCapturedTexts(const QStringList& texts) -{ - _capturedTexts = texts; -} -QStringList RegExpFilter::HotSpot::capturedTexts() const -{ - return _capturedTexts; -} +void RegExpFilter::process() { + const QString *text = buffer(); -void RegExpFilter::setRegExp(const QRegularExpression& regExp) -{ - _searchText = regExp; -} -QRegularExpression RegExpFilter::regExp() const -{ - return _searchText; -} -/*void RegExpFilter::reset(int) -{ - _buffer = QString(); -}*/ -void RegExpFilter::process() -{ - const QString* text = buffer(); - - Q_ASSERT( text ); + Q_ASSERT(text); // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely static const QString emptyString; - auto match = _searchText.match(emptyString, 0, - QRegularExpression::NormalMatch, QRegularExpression::AnchorAtOffsetMatchOption); + auto match = + _searchText.match(emptyString, 0, QRegularExpression::NormalMatch, + QRegularExpression::AnchorAtOffsetMatchOption); if (match.hasMatch()) return; @@ -381,11 +299,12 @@ void RegExpFilter::process() QString text = match.captured(i); captureList.append(text); } - + getLineColumn(match.capturedStart(), startLine, startColumn); getLineColumn(match.capturedEnd(), endLine, endColumn); - RegExpFilter::HotSpot* spot = newHotSpot(startLine, startColumn, endLine, endColumn); + RegExpFilter::HotSpot *spot = + newHotSpot(startLine, startColumn, endLine, endColumn); spot->setCapturedTexts(captureList); addHotSpot(spot); @@ -396,88 +315,84 @@ void RegExpFilter::process() } match = _searchText.match(*text, match.capturedEnd()); - } + } } -RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, - int endLine,int endColumn) -{ - HotSpot *spot = new RegExpFilter::HotSpot(startLine,startColumn, - endLine,endColumn); - spot->setColor(color()); +RegExpFilter::HotSpot *RegExpFilter::newHotSpot(int startLine, int startColumn, + int endLine, int endColumn) { + HotSpot *spot = + new RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn); + spot->setColor(color()); return spot; } -RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, - int endColumn) -{ - HotSpot *spot = new UrlFilter::HotSpot(startLine,startColumn, - endLine,endColumn); - connect(spot->getUrlObject(), &FilterObject::activated, this, &UrlFilter::activated); + +RegExpFilter::HotSpot *UrlFilter::newHotSpot(int startLine, int startColumn, + int endLine, int endColumn) { + HotSpot *spot = + new UrlFilter::HotSpot(startLine, startColumn, endLine, endColumn); + connect(spot->getUrlObject(), &FilterObject::activated, this, + &UrlFilter::activated); return spot; } -UrlFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) -: RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn) -, _urlObject(new FilterObject(this)) -{ +UrlFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, + int endColumn) + : RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn), + _urlObject(new FilterObject(this)) { setType(Link); } -UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const -{ +UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const { QString url = capturedTexts().constFirst(); - if ( FullUrlRegExp.match(url).hasMatch() ) + if (FullUrlRegExp.match(url).hasMatch()) return StandardUrl; - else if ( EmailAddressRegExp.match(url).hasMatch() ) + else if (EmailAddressRegExp.match(url).hasMatch()) return Email; - else if ( FilePathRegExp.match(url).hasMatch() ) + else if (FilePathRegExp.match(url).hasMatch()) return FilePath; else return Unknown; } -bool UrlFilter::HotSpot::hasClickAction(void) -{ +bool UrlFilter::HotSpot::hasClickAction(void) { const UrlType kind = urlType(); - if ( kind == StandardUrl ) { + if (kind == StandardUrl) { return true; - } else if ( kind == FilePath ) { + } else if (kind == FilePath) { return true; } return false; } -QString UrlFilter::HotSpot::clickActionToolTip(void) -{ +QString UrlFilter::HotSpot::clickActionToolTip(void) { const UrlType kind = urlType(); - if ( kind == StandardUrl ) { + if (kind == StandardUrl) { return tr("Follow link (ctrl + click)"); - } else if ( kind == FilePath ) { + } else if (kind == FilePath) { return tr("Follow path (ctrl + click)"); } return QString(); } -void UrlFilter::HotSpot::clickAction(void) -{ +void UrlFilter::HotSpot::clickAction(void) { QString url = capturedTexts().constFirst(); const UrlType kind = urlType(); - if ( kind == StandardUrl ) { + if (kind == StandardUrl) { // if the URL path does not include the protocol ( eg. "www.kde.org" ) then // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) if (!url.contains(QLatin1String("://"))) { url.prepend(QLatin1String("http://")); } - } else if ( kind == FilePath ) { - url.replace(QLatin1Char('\\'),QLatin1Char('/')); - url.replace(QLatin1Char('~'),QDir::homePath()); - if(url.startsWith(QLatin1String("/"))) { + } else if (kind == FilePath) { + url.replace(QLatin1Char('\\'), QLatin1Char('/')); + url.replace(QLatin1Char('~'), QDir::homePath()); + if (url.startsWith(QLatin1String("/"))) { url.prepend(QLatin1String("file://")); - } else if(url.startsWith(QLatin1String("."))) { + } else if (url.startsWith(QLatin1String("."))) { url.prepend(QLatin1String("relative:")); - } else if(url.startsWith(QLatin1String(".."))) { + } else if (url.startsWith(QLatin1String(".."))) { url.prepend(QLatin1String("relative:")); } else { url.prepend(QLatin1String("file:///")); @@ -486,139 +401,144 @@ void UrlFilter::HotSpot::clickAction(void) return; } - _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), QTermWidget::OpenFromClick); + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), + QTermWidget::OpenFromClick); } -// Note: Altering these regular expressions can have a major effect on the performance of the filters -// used for finding URLs in the text, especially if they are very general and could match very long -// pieces of text. -// Please be careful when altering them. +// Note: Altering these regular expressions can have a major effect on the +// performance of the filters used for finding URLs in the text, especially if +// they are very general and could match very long pieces of text. Please be +// careful when altering them. -//regexp matches: -// full url: -// protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot -const QRegularExpression UrlFilter::FullUrlRegExp(QLatin1String("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]")); +// regexp matches: +// full url: +// protocolname:// or www. followed by anything other than whitespaces, <, >, ' +// or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot +const QRegularExpression UrlFilter::FullUrlRegExp(QLatin1String( + "(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]")); // email address: // [word chars, dots or dashes]@[word chars, dots or dashes].[word chars] -const QRegularExpression UrlFilter::EmailAddressRegExp(QLatin1String("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b")); +const QRegularExpression UrlFilter::EmailAddressRegExp( + QLatin1String("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b")); // file path: -// '[drive letter]:\' '\\' '.\' or '..\' followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot -const QRegularExpression UrlFilter::WindowsFilePathRegExp(QLatin1String("([a-zA-Z]:\\\\|\\\\\\\\|\\.\\\\|\\.\\.\\\\)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]")); -// '/' '~/' './' or '../' followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot -const QRegularExpression UrlFilter::UnixFilePathRegExp(QLatin1String("((\\./|~/|\\.\\./)[^\\s<>'\"]+|/[^\\s<>'\"]+)[^!,\\.\\s<>'\"\\]]")); -const QRegularExpression UrlFilter::FilePathRegExp(QLatin1String("(")+ - WindowsFilePathRegExp.pattern()+QLatin1Char('|')+ - UnixFilePathRegExp.pattern()+ - QLatin1Char(')')); +// '[drive letter]:\' '\\' '.\' or '..\' followed by anything other than +// whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, +// comma and dot +const QRegularExpression UrlFilter::WindowsFilePathRegExp( + QLatin1String("([a-zA-Z]:\\\\|\\\\\\\\|\\.\\\\|\\.\\.\\\\)[^\\s<>'\"]+[^!," + "\\.\\s<>'\"\\]]")); +// '/' '~/' './' or '../' followed by anything other than whitespaces, <, >, ' +// or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot +const QRegularExpression UrlFilter::UnixFilePathRegExp(QLatin1String( + "((\\./|~/|\\.\\./)[^\\s<>'\"]+|/[^\\s<>'\"]+)[^!,\\.\\s<>'\"\\]]")); +const QRegularExpression UrlFilter::FilePathRegExp( + QLatin1String("(") + WindowsFilePathRegExp.pattern() + QLatin1Char('|') + + UnixFilePathRegExp.pattern() + QLatin1Char(')')); // matches full url or email address -const QRegularExpression UrlFilter::CompleteUrlRegExp(QLatin1Char('(')+ - FullUrlRegExp.pattern()+QLatin1Char('|')+ - EmailAddressRegExp.pattern()+QLatin1Char('|')+ - FilePathRegExp.pattern()+ - QLatin1Char(')')); +const QRegularExpression UrlFilter::CompleteUrlRegExp( + QLatin1Char('(') + FullUrlRegExp.pattern() + QLatin1Char('|') + + EmailAddressRegExp.pattern() + QLatin1Char('|') + FilePathRegExp.pattern() + + QLatin1Char(')')); -UrlFilter::UrlFilter() : RegExpFilter() -{ - setRegExp( CompleteUrlRegExp ); +UrlFilter::UrlFilter() : RegExpFilter() { + setRegExp(CompleteUrlRegExp); } -UrlFilter::HotSpot::~HotSpot() -{ - delete _urlObject; +UrlFilter::HotSpot::~HotSpot() { + delete _urlObject; } -void FilterObject::emitActivated(const QUrl& url, uint32_t opcode) -{ +void FilterObject::emitActivated(const QUrl &url, uint32_t opcode) { emit activated(url, opcode); } -FilterObject* UrlFilter::HotSpot::getUrlObject() const -{ - return _urlObject; -} +FilterObject *UrlFilter::HotSpot::getUrlObject() const { return _urlObject; } -QList UrlFilter::HotSpot::actions() -{ - QList list; +QList UrlFilter::HotSpot::actions() { + QList list; const UrlType kind = urlType(); - Q_ASSERT( kind == StandardUrl || kind == Email || kind == FilePath ); + Q_ASSERT(kind == StandardUrl || kind == Email || kind == FilePath); - if ( kind == StandardUrl ) { - QAction* openLinkAction = new QAction(_urlObject); - QAction* copyLinkAction = new QAction(_urlObject); + if (kind == StandardUrl) { + QAction *openLinkAction = new QAction(_urlObject); + QAction *copyLinkAction = new QAction(_urlObject); openLinkAction->setText(QObject::tr("Open Link")); copyLinkAction->setText(QObject::tr("Copy Link Address")); - QObject::connect( openLinkAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(openLinkAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); - // if the URL path does not include the protocol ( eg. "www.kde.org" ) then - // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) + // if the URL path does not include the protocol ( eg. "www.kde.org" ) + // then prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) if (!url.contains(QLatin1String("://"))) { url.prepend(QLatin1String("http://")); } - _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), QTermWidget::OpenFromContextMenu); + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), + QTermWidget::OpenFromContextMenu); }); - QObject::connect( copyLinkAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(copyLinkAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); QApplication::clipboard()->setText(url); }); list << openLinkAction; list << copyLinkAction; - } else if ( kind == Email ) { - QAction* sendEmailAction = new QAction(_urlObject); - QAction* copyEmailAction = new QAction(_urlObject); + } else if (kind == Email) { + QAction *sendEmailAction = new QAction(_urlObject); + QAction *copyEmailAction = new QAction(_urlObject); sendEmailAction->setText(QObject::tr("Send Email To...")); copyEmailAction->setText(QObject::tr("Copy Email Address")); - QObject::connect( sendEmailAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(sendEmailAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); url.prepend(QLatin1String("mailto:")); - _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), QTermWidget::OpenFromContextMenu); + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), + QTermWidget::OpenFromContextMenu); }); - QObject::connect( copyEmailAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(copyEmailAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); QApplication::clipboard()->setText(url); }); list << sendEmailAction; list << copyEmailAction; - } else if ( kind == FilePath ) { - QAction* openPathAction = new QAction(_urlObject); - QAction* openContainingPathAction = new QAction(_urlObject); - QAction* copyPathAction = new QAction(_urlObject); + } else if (kind == FilePath) { + QAction *openPathAction = new QAction(_urlObject); + QAction *openContainingPathAction = new QAction(_urlObject); + QAction *copyPathAction = new QAction(_urlObject); openPathAction->setText(QObject::tr("Open Path")); openContainingPathAction->setText(QObject::tr("Open Containing Folder")); copyPathAction->setText(QObject::tr("Copy Path")); - QObject::connect( openPathAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(openPathAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); - url.replace(QLatin1Char('\\'),QLatin1Char('/')); - url.replace(QLatin1Char('~'),QDir::homePath()); - if(url.startsWith(QLatin1String("/"))) { + url.replace(QLatin1Char('\\'), QLatin1Char('/')); + url.replace(QLatin1Char('~'), QDir::homePath()); + if (url.startsWith(QLatin1String("/"))) { url.prepend(QLatin1String("file://")); - } else if(url.startsWith(QLatin1String("."))) { + } else if (url.startsWith(QLatin1String("."))) { url.prepend(QLatin1String("relative:")); - } else if(url.startsWith(QLatin1String(".."))) { + } else if (url.startsWith(QLatin1String(".."))) { url.prepend(QLatin1String("relative:")); } else { url.prepend(QLatin1String("file:///")); } - _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), QTermWidget::OpenFromContextMenu); + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), + QTermWidget::OpenFromContextMenu); }); - QObject::connect( openContainingPathAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(openContainingPathAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); - url.replace(QLatin1Char('\\'),QLatin1Char('/')); - url.replace(QLatin1Char('~'),QDir::homePath()); - if(url.startsWith(QLatin1String("/"))) { + url.replace(QLatin1Char('\\'), QLatin1Char('/')); + url.replace(QLatin1Char('~'), QDir::homePath()); + if (url.startsWith(QLatin1String("/"))) { url.prepend(QLatin1String("file://")); - } else if(url.startsWith(QLatin1String("."))) { + } else if (url.startsWith(QLatin1String("."))) { url.prepend(QLatin1String("relative:")); - } else if(url.startsWith(QLatin1String(".."))) { + } else if (url.startsWith(QLatin1String(".."))) { url.prepend(QLatin1String("relative:")); } else { url.prepend(QLatin1String("file:///")); } - _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), QTermWidget::OpenContainingFromContextMenu); + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), + QTermWidget::OpenContainingFromContextMenu); }); - QObject::connect( copyPathAction , &QAction::triggered , _urlObject , [&](void) { + QObject::connect(copyPathAction, &QAction::triggered, _urlObject, [&](void) { QString url = capturedTexts().constFirst(); QApplication::clipboard()->setText(url); }); diff --git a/lib/qtermwidget/Filter.h b/lib/qtermwidget/Filter.h index 2ad71f5d..f05a5961 100644 --- a/lib/qtermwidget/Filter.h +++ b/lib/qtermwidget/Filter.h @@ -1,20 +1,20 @@ /* - Copyright 2007-2008 by Robert Knight - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2007-2008 by Robert Knight + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef FILTER_H @@ -64,70 +64,68 @@ class Filter : public QObject * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. These actions may then be displayed in a popup menu or toolbar for example. */ - class HotSpot - { + class HotSpot { public: - /** - * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) - * in a block of text. - */ - HotSpot(int startLine , int startColumn , int endLine , int endColumn); - virtual ~HotSpot(); - - enum Type - { + /** + * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) + * in a block of text. + */ + HotSpot(int startLine , int startColumn , int endLine , int endColumn); + virtual ~HotSpot(); + + enum Type { // the type of the hotspot is not specified NotSpecified, // this hotspot represents a clickable link Link, // this hotspot represents a marker Marker - }; - - /** Returns the line when the hotspot area starts */ - int startLine() const; - /** Returns the line where the hotspot area ends */ - int endLine() const; - /** Returns the column on startLine() where the hotspot area starts */ - int startColumn() const; - /** Returns the column on endLine() where the hotspot area ends */ - int endColumn() const; - - /** - * Returns the type of the hotspot. This is usually used as a hint for views on how to represent - * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them - */ - Type type() const; - QColor color() const; - void setColor(const QColor& color); - /** - * Causes the an action associated with a hotspot to be triggered. - * - * @param action The action to trigger. This is - * typically empty ( in which case the default action should be performed ) or - * one of the object names from the actions() list. In which case the associated - * action should be performed. - */ - virtual void clickAction(void) = 0; - virtual QString clickActionToolTip(void) = 0; - virtual bool hasClickAction(void) = 0; - /** - * Returns a list of actions associated with the hotspot which can be used in a - * menu or toolbar - */ - virtual QList actions(); + }; + + /** Returns the line when the hotspot area starts */ + int startLine() const; + /** Returns the line where the hotspot area ends */ + int endLine() const; + /** Returns the column on startLine() where the hotspot area starts */ + int startColumn() const; + /** Returns the column on endLine() where the hotspot area ends */ + int endColumn() const; + + /** + * Returns the type of the hotspot. This is usually used as a hint for views on how to represent + * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them + */ + Type type() const; + QColor color() const; + void setColor(const QColor& color); + /** + * Causes the an action associated with a hotspot to be triggered. + * + * @param action The action to trigger. This is + * typically empty ( in which case the default action should be performed ) or + * one of the object names from the actions() list. In which case the associated + * action should be performed. + */ + virtual void clickAction(void) = 0; + virtual QString clickActionToolTip(void) = 0; + virtual bool hasClickAction(void) = 0; + /** + * Returns a list of actions associated with the hotspot which can be used in a + * menu or toolbar + */ + virtual QList actions(); protected: - /** Sets the type of a hotspot. This should only be set once */ - void setType(Type type); + /** Sets the type of a hotspot. This should only be set once */ + void setType(Type type); private: - int _startLine; - int _startColumn; - int _endLine; - int _endColumn; - Type _type; - QColor _color; + int _startLine; + int _startColumn; + int _endLine; + int _endColumn; + Type _type; + QColor _color; }; /** Constructs a new filter. */ @@ -191,8 +189,7 @@ class RegExpFilter : public Filter * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * matched by the filter's regular expression. */ - class HotSpot : public Filter::HotSpot - { + class HotSpot : public Filter::HotSpot { public: HotSpot(int startLine, int startColumn, int endLine , int endColumn); void clickAction(void) override; @@ -257,8 +254,7 @@ class UrlFilter : public RegExpFilter * Hotspot type created by UrlFilter instances. The activate() method opens a web browser * at the given URL when called. */ - class HotSpot : public RegExpFilter::HotSpot - { + class HotSpot : public RegExpFilter::HotSpot { public: HotSpot(int startLine,int startColumn,int endLine,int endColumn); ~HotSpot() override; @@ -276,8 +272,7 @@ class UrlFilter : public RegExpFilter bool hasClickAction(void) override; private: - enum UrlType - { + enum UrlType { StandardUrl, Email, FilePath, diff --git a/lib/qtermwidget/History.cpp b/lib/qtermwidget/History.cpp index 3e15f4be..1a14f6b7 100644 --- a/lib/qtermwidget/History.cpp +++ b/lib/qtermwidget/History.cpp @@ -1,29 +1,29 @@ /* - This file is part of Konsole, an X terminal. - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "History.h" #include -#include -#include #include +#include +#include #if defined(Q_OS_WIN) #include #else @@ -36,946 +36,733 @@ #include // Reasonable line size -#define LINE_SIZE 1024 +#define LINE_SIZE 1024 /* - An arbitrary long scroll. + An arbitrary long scroll. - One can modify the scroll only by adding either cells - or newlines, but access it randomly. + One can modify the scroll only by adding either cells + or newlines, but access it randomly. - The model is that of an arbitrary wide typewriter scroll - in that the scroll is a serie of lines and each line is - a serie of cells with no overwriting permitted. + The model is that of an arbitrary wide typewriter scroll + in that the scroll is a serie of lines and each line is + a serie of cells with no overwriting permitted. - The implementation provides arbitrary length and numbers - of cells and line/column indexed read access to the scroll - at constant costs. + The implementation provides arbitrary length and numbers + of cells and line/column indexed read access to the scroll + at constant costs. -KDE4: Can we use QTemporaryFile here, instead of KTempFile? + KDE4: Can we use QTemporaryFile here, instead of KTempFile? -FIXME: some complain about the history buffer consuming the - memory of their machines. This problem is critical - since the history does not behave gracefully in cases - where the memory is used up completely. + FIXME: some complain about the history buffer consuming the + memory of their machines. This problem is critical + since the history does not behave gracefully in cases + where the memory is used up completely. - I put in a workaround that should handle it problem - now gracefully. I'm not satisfied with the solution. + I put in a workaround that should handle it problem + now gracefully. I'm not satisfied with the solution. -FIXME: Terminating the history is not properly indicated - in the menu. We should throw a signal. + FIXME: Terminating the history is not properly indicated + in the menu. We should throw a signal. -FIXME: There is noticeable decrease in speed, also. Perhaps, - there whole feature needs to be revisited therefore. - Disadvantage of a more elaborated, say block-oriented - scheme with wrap around would be it's complexity. + FIXME: There is noticeable decrease in speed, also. Perhaps, + there whole feature needs to be revisited therefore. + Disadvantage of a more elaborated, say block-oriented + scheme with wrap around would be it's complexity. */ -//FIXME: temporary replacement for tmpfile -// this is here one for debugging purpose. - -//#define tmpfile xTmpFile - -// History File /////////////////////////////////////////// - /* A Row(X) data type which allows adding elements to the end. */ HistoryFile::HistoryFile() - : ion(-1), - length(0), - fileMap(nullptr), - readWriteBalance(0) -{ - if (tmpFile.open()) - { - tmpFile.setAutoRemove(true); - ion = tmpFile.handle(); - } -} - -HistoryFile::~HistoryFile() -{ + : ion(-1) + , length(0) + , fileMap(nullptr) + , readWriteBalance(0) { + if (tmpFile.open()) { + tmpFile.setAutoRemove(true); + ion = tmpFile.handle(); + } +} + +HistoryFile::~HistoryFile() { if (fileMap) unmap(); } -//TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, -//(ie. larger than available memory). HistoryFile::map() should only map in sections of the file at a time, -//to avoid this. -void HistoryFile::map() -{ - Q_ASSERT( fileMap == nullptr ); +// TODO: Mapping the entire file in will cause problems if the history file +// becomes exceedingly large, (ie. larger than available memory). +//HistoryFile::map() should only map in sections of the file at a time, to avoid +// this. +void HistoryFile::map() { + Q_ASSERT(fileMap == nullptr); #if defined(Q_OS_WIN) readWriteBalance = 0; fileMap = nullptr; #else - fileMap = (char*)mmap( nullptr , length , PROT_READ , MAP_PRIVATE , ion , 0 ); + fileMap = (char *)mmap(nullptr, length, PROT_READ, MAP_PRIVATE, ion, 0); - //if mmap'ing fails, fall back to the read-lseek combination - if ( fileMap == MAP_FAILED ) - { - readWriteBalance = 0; - fileMap = nullptr; + // if mmap'ing fails, fall back to the read-lseek combination + if (fileMap == MAP_FAILED) { + readWriteBalance = 0; + fileMap = nullptr; } #endif } -void HistoryFile::unmap() -{ +void HistoryFile::unmap() { #if defined(Q_OS_WIN) fileMap = nullptr; #else - int result = munmap( fileMap , length ); - Q_ASSERT( result == 0 ); Q_UNUSED( result ); + int result = munmap(fileMap, length); + Q_ASSERT(result == 0); + Q_UNUSED(result); #endif - fileMap = nullptr; } -bool HistoryFile::isMapped() const -{ - return (fileMap != nullptr); +bool HistoryFile::isMapped() const { + return (fileMap != nullptr); } -void HistoryFile::add(const unsigned char* bytes, int len) -{ - if ( fileMap ) - unmap(); +void HistoryFile::add(const unsigned char *bytes, int len) { + if (fileMap) + unmap(); - readWriteBalance++; + readWriteBalance++; - int rc = 0; + int rc = 0; #if defined(Q_OS_WIN) - tmpFile.seek(length); - rc = tmpFile.write((const char*)bytes,len); + tmpFile.seek(length); + rc = tmpFile.write((const char *)bytes, len); #else - rc = lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } - rc = write(ion,bytes,len); if (rc < 0) { perror("HistoryFile::add.write"); return; } + rc = lseek(ion, length, SEEK_SET); + if (rc < 0) { + perror("HistoryFile::add.seek"); + return; + } + rc = write(ion, bytes, len); + if (rc < 0) { + perror("HistoryFile::add.write"); + return; + } #endif - length += rc; -} - -void HistoryFile::get(unsigned char* bytes, int len, int loc) -{ - //count number of get() calls vs. number of add() calls. - //If there are many more get() calls compared with add() - //calls (decided by using MAP_THRESHOLD) then mmap the log - //file to improve performance. - readWriteBalance--; - if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) - map(); - - if ( fileMap ) - { - for (int i=0;i length) - fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); -#if defined(Q_OS_WIN) - tmpFile.seek(loc); - rc = tmpFile.read((char*)bytes,len); -#else - rc = lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } - rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } + length += rc; +} + +void HistoryFile::get(unsigned char *bytes, int len, int loc) { + // count number of get() calls vs. number of add() calls. + // If there are many more get() calls compared with add() + // calls (decided by using MAP_THRESHOLD) then mmap the log + // file to improve performance. + readWriteBalance--; + if (!fileMap && readWriteBalance < MAP_THRESHOLD) + map(); + + if (fileMap) { + for (int i = 0; i < len; i++) + bytes[i] = fileMap[loc + i]; + } else { + int rc = 0; + + if (loc < 0 || len < 0 || loc + len > length) + fprintf(stderr, "getHist(...,%d,%d): invalid args.\n", len, loc); + #if defined(Q_OS_WIN) + tmpFile.seek(loc); + rc = tmpFile.read((char *)bytes, len); + #else + rc = lseek(ion, loc, SEEK_SET); + if (rc < 0) { + perror("HistoryFile::get.seek"); + return; + } + rc = read(ion, bytes, len); + if (rc < 0) { + perror("HistoryFile::get.read"); + return; + } #endif - } + } } -int HistoryFile::len() -{ - return length; +int HistoryFile::len() { + return length; } - -// History Scroll abstract base class ////////////////////////////////////// - - -HistoryScroll::HistoryScroll(HistoryType* t) - : m_histType(t) -{ +HistoryScroll::HistoryScroll(HistoryType *t) : m_histType(t) { } -HistoryScroll::~HistoryScroll() -{ - delete m_histType; +HistoryScroll::~HistoryScroll() { + delete m_histType; } -bool HistoryScroll::hasScroll() -{ - return true; +bool HistoryScroll::hasScroll() { + return true; } -// History Scroll File ////////////////////////////////////// - /* - The history scroll makes a Row(Row(Cell)) from - two history buffers. The index buffer contains - start of line positions which refers to the cells - buffer. - - Note that index[0] addresses the second line - (line #1), while the first line (line #0) starts - at 0 in cells. + The history scroll makes a Row(Row(Cell)) from + two history buffers. The index buffer contains + start of line positions which refers to the cells + buffer. + + Note that index[0] addresses the second line + (line #1), while the first line (line #0) starts + at 0 in cells. */ - HistoryScrollFile::HistoryScrollFile(const QString &logFileName) - : HistoryScroll(new HistoryTypeFile(logFileName)), - m_logFileName(logFileName) -{ + : HistoryScroll(new HistoryTypeFile(logFileName)) + , m_logFileName(logFileName) { } -HistoryScrollFile::~HistoryScrollFile() -{ +HistoryScrollFile::~HistoryScrollFile() { } -int HistoryScrollFile::getLines() -{ - return index.len() / sizeof(int); +int HistoryScrollFile::getLines() { + return index.len() / sizeof(int); } -int HistoryScrollFile::getLineLen(int lineno) -{ - return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character); +int HistoryScrollFile::getLineLen(int lineno) { + return (startOfLine(lineno + 1) - startOfLine(lineno)) / sizeof(Character); } -bool HistoryScrollFile::isWrappedLine(int lineno) -{ - if (lineno>=0 && lineno <= getLines()) { - unsigned char flag; - lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); - return flag; - } - return false; +bool HistoryScrollFile::isWrappedLine(int lineno) { + if (lineno >= 0 && lineno <= getLines()) { + unsigned char flag; + lineflags.get((unsigned char *)&flag, sizeof(unsigned char), + (lineno) * sizeof(unsigned char)); + return flag; + } + return false; } -int HistoryScrollFile::startOfLine(int lineno) -{ - if (lineno <= 0) return 0; - if (lineno <= getLines()) - { - if (!index.isMapped()) - index.map(); +int HistoryScrollFile::startOfLine(int lineno) { + if (lineno <= 0) + return 0; + if (lineno <= getLines()) { + if (!index.isMapped()) + index.map(); - int res = 0; - index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); - return res; + int res = 0; + index.get((unsigned char *)&res, sizeof(int), (lineno - 1) * sizeof(int)); + return res; } - return cells.len(); + return cells.len(); } -void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) -{ - cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); +void HistoryScrollFile::getCells(int lineno, int colno, int count, + Character res[]) { + cells.get((unsigned char *)res, count * sizeof(Character), + startOfLine(lineno) + colno * sizeof(Character)); } -void HistoryScrollFile::addCells(const Character text[], int count) -{ - cells.add((unsigned char*)text,count*sizeof(Character)); +void HistoryScrollFile::addCells(const Character text[], int count) { + cells.add((unsigned char *)text, count * sizeof(Character)); } -void HistoryScrollFile::addLine(bool previousWrapped) -{ - if (index.isMapped()) - index.unmap(); +void HistoryScrollFile::addLine(bool previousWrapped) { + if (index.isMapped()) + index.unmap(); - int locn = cells.len(); - index.add((unsigned char*)&locn,sizeof(int)); - unsigned char flags = previousWrapped ? 0x01 : 0x00; - lineflags.add((unsigned char*)&flags,sizeof(unsigned char)); + int locn = cells.len(); + index.add((unsigned char *)&locn, sizeof(int)); + unsigned char flags = previousWrapped ? 0x01 : 0x00; + lineflags.add((unsigned char *)&flags, sizeof(unsigned char)); } - -// History Scroll Buffer ////////////////////////////////////// HistoryScrollBuffer::HistoryScrollBuffer(unsigned int maxLineCount) - : HistoryScroll(new HistoryTypeBuffer(maxLineCount)) - ,_historyBuffer() - ,_maxLineCount(0) - ,_usedLines(0) - ,_head(0) -{ - setMaxNbLines(maxLineCount); + : HistoryScroll(new HistoryTypeBuffer(maxLineCount)), _historyBuffer(), + _maxLineCount(0), _usedLines(0), _head(0) { + setMaxNbLines(maxLineCount); } -HistoryScrollBuffer::~HistoryScrollBuffer() -{ - delete[] _historyBuffer; +HistoryScrollBuffer::~HistoryScrollBuffer() { + delete[] _historyBuffer; } -void HistoryScrollBuffer::addCellsVector(const QVector& cells) -{ +void HistoryScrollBuffer::addCellsVector(const QVector &cells) { _head++; - if ( _usedLines < _maxLineCount ) + if (_usedLines < _maxLineCount) _usedLines++; - if ( _head >= _maxLineCount ) - { + if (_head >= _maxLineCount) { _head = 0; } - _historyBuffer[bufferIndex(_usedLines-1)] = cells; - _wrappedLine[bufferIndex(_usedLines-1)] = false; + _historyBuffer[bufferIndex(_usedLines - 1)] = cells; + _wrappedLine[bufferIndex(_usedLines - 1)] = false; } -void HistoryScrollBuffer::addCells(const Character a[], int count) -{ - HistoryLine newLine(count); - std::copy(a,a+count,newLine.begin()); - addCellsVector(newLine); +void HistoryScrollBuffer::addCells(const Character a[], int count) { + HistoryLine newLine(count); + std::copy(a, a + count, newLine.begin()); + + addCellsVector(newLine); } -void HistoryScrollBuffer::addLine(bool previousWrapped) -{ - _wrappedLine[bufferIndex(_usedLines-1)] = previousWrapped; +void HistoryScrollBuffer::addLine(bool previousWrapped) { + _wrappedLine[bufferIndex(_usedLines - 1)] = previousWrapped; } -int HistoryScrollBuffer::getLines() -{ - return _usedLines; +int HistoryScrollBuffer::getLines() { + return _usedLines; } -int HistoryScrollBuffer::getLineLen(int lineNumber) -{ - Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); +int HistoryScrollBuffer::getLineLen(int lineNumber) { + Q_ASSERT(lineNumber >= 0 && lineNumber < _maxLineCount); - if ( lineNumber < _usedLines ) - { - return _historyBuffer[bufferIndex(lineNumber)].size(); - } - else - { - return 0; - } + if (lineNumber < _usedLines) { + return _historyBuffer[bufferIndex(lineNumber)].size(); + } else { + return 0; + } } -bool HistoryScrollBuffer::isWrappedLine(int lineNumber) -{ - Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); +bool HistoryScrollBuffer::isWrappedLine(int lineNumber) { + Q_ASSERT(lineNumber >= 0 && lineNumber < _maxLineCount); - if (lineNumber < _usedLines) - { - return _wrappedLine[bufferIndex(lineNumber)]; - } - else - return false; + if (lineNumber < _usedLines) { + return _wrappedLine[bufferIndex(lineNumber)]; + } else + return false; } -void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character buffer[]) -{ - if ( count == 0 ) return; +void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, + Character buffer[]) { + if (count == 0) + return; - Q_ASSERT( lineNumber < _maxLineCount ); + Q_ASSERT(lineNumber < _maxLineCount); - if (lineNumber >= _usedLines) - { - memset(static_cast(buffer), 0, count * sizeof(Character)); - return; - } + if (lineNumber >= _usedLines) { + memset(static_cast(buffer), 0, count * sizeof(Character)); + return; + } - const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; + const HistoryLine &line = _historyBuffer[bufferIndex(lineNumber)]; - Q_ASSERT( startColumn <= line.size() - count ); + Q_ASSERT(startColumn <= line.size() - count); - memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); + memcpy(buffer, line.constData() + startColumn, count * sizeof(Character)); } -void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) -{ - HistoryLine* oldBuffer = _historyBuffer; - HistoryLine* newBuffer = new HistoryLine[lineCount]; +void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { + HistoryLine *oldBuffer = _historyBuffer; + HistoryLine *newBuffer = new HistoryLine[lineCount]; - for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) - { + for (int i = 0; i < qMin(_usedLines, (int)lineCount); i++) { newBuffer[i] = oldBuffer[bufferIndex(i)]; } - _usedLines = qMin(_usedLines,(int)lineCount); + _usedLines = qMin(_usedLines, (int)lineCount); _maxLineCount = lineCount; - _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; + _head = (_usedLines == _maxLineCount) ? 0 : _usedLines - 1; _historyBuffer = newBuffer; delete[] oldBuffer; _wrappedLine.resize(lineCount); - dynamic_cast(m_histType)->m_nbLines = lineCount; + dynamic_cast(m_histType)->m_nbLines = lineCount; } -int HistoryScrollBuffer::bufferIndex(int lineNumber) const -{ - Q_ASSERT( lineNumber >= 0 ); - Q_ASSERT( lineNumber < _maxLineCount ); - Q_ASSERT( (_usedLines == _maxLineCount) || lineNumber <= _head ); +int HistoryScrollBuffer::bufferIndex(int lineNumber) const { + Q_ASSERT(lineNumber >= 0); + Q_ASSERT(lineNumber < _maxLineCount); + Q_ASSERT((_usedLines == _maxLineCount) || lineNumber <= _head); - if ( _usedLines == _maxLineCount ) - { - return (_head+lineNumber+1) % _maxLineCount; - } - else - { + if (_usedLines == _maxLineCount) { + return (_head + lineNumber + 1) % _maxLineCount; + } else { return lineNumber; } } - -// History Scroll None ////////////////////////////////////// - -HistoryScrollNone::HistoryScrollNone() - : HistoryScroll(new HistoryTypeNone()) -{ -} - -HistoryScrollNone::~HistoryScrollNone() -{ -} - -bool HistoryScrollNone::hasScroll() -{ - return false; -} - -int HistoryScrollNone::getLines() -{ - return 0; -} - -int HistoryScrollNone::getLineLen(int) -{ - return 0; -} - -bool HistoryScrollNone::isWrappedLine(int /*lineno*/) -{ - return false; -} - -void HistoryScrollNone::getCells(int, int, int, Character []) -{ -} - -void HistoryScrollNone::addCells(const Character [], int) -{ -} - -void HistoryScrollNone::addLine(bool) -{ -} - -// History Scroll BlockArray ////////////////////////////////////// +HistoryScrollNone::HistoryScrollNone() : HistoryScroll(new HistoryTypeNone()) {} +HistoryScrollNone::~HistoryScrollNone() {} +bool HistoryScrollNone::hasScroll() { return false; } +int HistoryScrollNone::getLines() { return 0; } +int HistoryScrollNone::getLineLen(int) { return 0; } +bool HistoryScrollNone::isWrappedLine(int /*lineno*/) { return false; } +void HistoryScrollNone::getCells(int, int, int, Character[]) {} +void HistoryScrollNone::addCells(const Character[], int) {} +void HistoryScrollNone::addLine(bool) {} HistoryScrollBlockArray::HistoryScrollBlockArray(size_t size) - : HistoryScroll(new HistoryTypeBlockArray(size)) -{ - m_blockArray.setHistorySize(size); // nb. of lines. + : HistoryScroll(new HistoryTypeBlockArray(size)) { + m_blockArray.setHistorySize(size); // nb. of lines. } -HistoryScrollBlockArray::~HistoryScrollBlockArray() -{ +HistoryScrollBlockArray::~HistoryScrollBlockArray() { } -int HistoryScrollBlockArray::getLines() -{ - return m_lineLengths.count(); +int HistoryScrollBlockArray::getLines() { + return m_lineLengths.count(); } -int HistoryScrollBlockArray::getLineLen(int lineno) -{ - if ( m_lineLengths.contains(lineno) ) +int HistoryScrollBlockArray::getLineLen(int lineno) { + if (m_lineLengths.contains(lineno)) return m_lineLengths[lineno]; else return 0; } -bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) -{ - return false; +bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) { + return false; } -void HistoryScrollBlockArray::getCells(int lineno, int colno, - int count, Character res[]) -{ - if (!count) return; +void HistoryScrollBlockArray::getCells(int lineno, int colno, int count, + Character res[]) { + if (!count) + return; - const Block *b = m_blockArray.at(lineno); + const Block *b = m_blockArray.at(lineno); - if (!b) { - memset(static_cast(res), 0, count * sizeof(Character)); // still better than random data - return; - } + if (!b) { + memset(static_cast(res), 0, + count * sizeof(Character)); // still better than random data + return; + } - Q_ASSERT(((colno + count) * sizeof(Character)) < ENTRIES); - memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); + Q_ASSERT(((colno + count) * sizeof(Character)) < ENTRIES); + memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); } -void HistoryScrollBlockArray::addCells(const Character a[], int count) -{ - Block *b = m_blockArray.lastBlock(); - - if (!b) return; +void HistoryScrollBlockArray::addCells(const Character a[], int count) { + Block *b = m_blockArray.lastBlock(); - // put cells in block's data - Q_ASSERT((count * sizeof(Character)) < ENTRIES); + if (!b) + return; - memset(b->data, 0, sizeof(b->data)); + // put cells in block's data + Q_ASSERT((count * sizeof(Character)) < ENTRIES); - memcpy(b->data, a, count * sizeof(Character)); - b->size = count * sizeof(Character); + memset(b->data, 0, sizeof(b->data)); - size_t res = m_blockArray.newBlock(); - Q_ASSERT(res > 0); - Q_UNUSED( res ); + memcpy(b->data, a, count * sizeof(Character)); + b->size = count * sizeof(Character); - m_lineLengths.insert(m_blockArray.getCurrent(), count); -} + size_t res = m_blockArray.newBlock(); + Q_ASSERT(res > 0); + Q_UNUSED(res); -void HistoryScrollBlockArray::addLine(bool) -{ + m_lineLengths.insert(m_blockArray.getCurrent(), count); } -//////////////////////////////////////////////////////////////// -// Compact History Scroll ////////////////////////////////////// -//////////////////////////////////////////////////////////////// -void* CompactHistoryBlock::allocate ( size_t length ) -{ - Q_ASSERT ( length > 0 ); - if ( tail-blockStart+length > blockLength ) - return nullptr; - - void* block = tail; - tail += length; - allocCount++; - return block; +void HistoryScrollBlockArray::addLine(bool) { } -void CompactHistoryBlock::deallocate ( ) -{ - allocCount--; - Q_ASSERT ( allocCount >= 0 ); -} +void *CompactHistoryBlock::allocate(size_t length) { + Q_ASSERT(length > 0); + if (tail - blockStart + length > blockLength) + return nullptr; -void* CompactHistoryBlockList::allocate(size_t size) -{ - CompactHistoryBlock* block; - if ( list.isEmpty() || list.last()->remaining() < size) - { - block = new CompactHistoryBlock(); - list.append ( block ); - } - else - { - block = list.last(); - } - return block->allocate(size); + void *block = tail; + tail += length; + allocCount++; + return block; } -void CompactHistoryBlockList::deallocate(void* ptr) -{ - Q_ASSERT( !list.isEmpty()); - - int i=0; - CompactHistoryBlock *block = list.at(i); - while ( icontains(ptr) ) - { - i++; - block=list.at(i); - } - - Q_ASSERT( ideallocate(); - - if (!block->isInUse()) - { - list.removeAt(i); - delete block; - } +void CompactHistoryBlock::deallocate() { + allocCount--; + Q_ASSERT(allocCount >= 0); } -CompactHistoryBlockList::~CompactHistoryBlockList() -{ - qDeleteAll ( list.begin(), list.end() ); - list.clear(); -} - -void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& blockList) -{ - return blockList.allocate(size); -} - -CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) - : blockList(bList), - formatLength(0) -{ - length=line.size(); - - if (!line.empty()) { - formatLength=1; - int k=1; - - // count number of different formats in this text line - Character c = line[0]; - while ( kremaining() < size) { + block = new CompactHistoryBlock(); + list.append(block); + } else { + block = list.last(); } - } + return block->allocate(size); } -CompactHistoryLine::~CompactHistoryLine() -{ - if (length>0) { - blockList.deallocate(text); - blockList.deallocate(formatArray); - } - blockList.deallocate(this); -} +void CompactHistoryBlockList::deallocate(void *ptr) { + Q_ASSERT(!list.isEmpty()); -void CompactHistoryLine::getCharacter ( int index, Character &r ) -{ - Q_ASSERT ( index < length ); - int formatPos=0; - while ( ( formatPos+1 ) < formatLength && index >= formatArray[formatPos+1].startPos ) - formatPos++; + int i = 0; + CompactHistoryBlock *block = list.at(i); + while (i < list.size() && !block->contains(ptr)) { + i++; + block = list.at(i); + } - r.character=text[index]; - r.rendition = formatArray[formatPos].rendition; - r.foregroundColor = formatArray[formatPos].fgColor; - r.backgroundColor = formatArray[formatPos].bgColor; -} + Q_ASSERT(i < list.size()); -void CompactHistoryLine::getCharacters ( Character* array, int length, int startColumn ) -{ - Q_ASSERT ( startColumn >= 0 && length >= 0 ); - Q_ASSERT ( startColumn+length <= ( int ) getLength() ); + block->deallocate(); - for ( int i=startColumn; iisInUse()) { + list.removeAt(i); + delete block; + } } -CompactHistoryScroll::CompactHistoryScroll ( unsigned int maxLineCount ) - : HistoryScroll ( new CompactHistoryType ( maxLineCount ) ) - ,lines() - ,blockList() -{ - setMaxNbLines ( maxLineCount ); +CompactHistoryBlockList::~CompactHistoryBlockList() { + qDeleteAll(list.begin(), list.end()); + list.clear(); +} + +void *CompactHistoryLine::operator new(size_t size, CompactHistoryBlockList &blockList) { + return blockList.allocate(size); +} + +CompactHistoryLine::CompactHistoryLine(const TextLine &line, + CompactHistoryBlockList &bList) + : blockList(bList), formatLength(0) { + length = line.size(); + + if (!line.empty()) { + formatLength = 1; + int k = 1; + + // count number of different formats in this text line + Character c = line[0]; + while (k < length) { + if (!(line[k].equalsFormat(c))) { + formatLength++; // format change detected + c = line[k]; + } + k++; + } + + formatArray = (CharacterFormat *)blockList.allocate( + sizeof(CharacterFormat) * formatLength); + Q_ASSERT(formatArray != nullptr); + text = (quint16 *)blockList.allocate(sizeof(quint16) * line.size()); + Q_ASSERT(text != nullptr); + + length = line.size(); + wrapped = false; + + // record formats and their positions in the format array + c = line[0]; + formatArray[0].setFormat(c); + formatArray[0].startPos = 0; // there's always at least 1 format (for the + // entire line, unless a change happens) + + k = 1; // look for possible format changes + int j = 1; + while (k < length && j < formatLength) { + if (!(line[k].equalsFormat(c))) { + c = line[k]; + formatArray[j].setFormat(c); + formatArray[j].startPos = k; + j++; + } + k++; + } + + // copy character values + for (int i = 0; i < line.size(); i++) { + text[i] = line[i].character; + } + } } -CompactHistoryScroll::~CompactHistoryScroll() -{ - qDeleteAll ( lines.begin(), lines.end() ); - lines.clear(); +CompactHistoryLine::~CompactHistoryLine() { + if (length > 0) { + blockList.deallocate(text); + blockList.deallocate(formatArray); + } + blockList.deallocate(this); } -void CompactHistoryScroll::addCellsVector ( const TextLine& cells ) -{ - CompactHistoryLine *line; - line = new(blockList) CompactHistoryLine ( cells, blockList ); - - if ( lines.size() > ( int ) _maxLineCount ) - { - delete lines.takeAt ( 0 ); - } - lines.append ( line ); -} +void CompactHistoryLine::getCharacter(int index, Character &r) { + Q_ASSERT(index < length); + int formatPos = 0; + while ((formatPos + 1) < formatLength && + index >= formatArray[formatPos + 1].startPos) + formatPos++; -void CompactHistoryScroll::addCells ( const Character a[], int count ) -{ - TextLine newLine ( count ); - std::copy ( a,a+count,newLine.begin() ); - addCellsVector ( newLine ); + r.character = text[index]; + r.rendition = formatArray[formatPos].rendition; + r.foregroundColor = formatArray[formatPos].fgColor; + r.backgroundColor = formatArray[formatPos].bgColor; } -void CompactHistoryScroll::addLine ( bool previousWrapped ) -{ - CompactHistoryLine *line = lines.last(); - line->setWrapped(previousWrapped); -} +void CompactHistoryLine::getCharacters(Character *array, int length, + int startColumn) { + Q_ASSERT(startColumn >= 0 && length >= 0); + Q_ASSERT(startColumn + length <= (int)getLength()); -int CompactHistoryScroll::getLines() -{ - return lines.size(); + for (int i = startColumn; i < length + startColumn; i++) { + getCharacter(i, array[i - startColumn]); + } } -int CompactHistoryScroll::getLineLen ( int lineNumber ) -{ - Q_ASSERT ( lineNumber >= 0 && lineNumber < lines.size() ); - CompactHistoryLine* line = lines[lineNumber]; - return line->getLength(); +CompactHistoryScroll::CompactHistoryScroll(unsigned int maxLineCount) + : HistoryScroll(new CompactHistoryType(maxLineCount)), lines(), + blockList() { + setMaxNbLines(maxLineCount); } - -void CompactHistoryScroll::getCells ( int lineNumber, int startColumn, int count, Character buffer[] ) -{ - if ( count == 0 ) return; - Q_ASSERT ( lineNumber < lines.size() ); - CompactHistoryLine* line = lines[lineNumber]; - Q_ASSERT ( startColumn >= 0 ); - Q_ASSERT ( (unsigned int)startColumn <= line->getLength() - count ); - line->getCharacters ( buffer, count, startColumn ); +CompactHistoryScroll::~CompactHistoryScroll() { + qDeleteAll(lines.begin(), lines.end()); + lines.clear(); } -void CompactHistoryScroll::setMaxNbLines ( unsigned int lineCount ) -{ - _maxLineCount = lineCount; +void CompactHistoryScroll::addCellsVector(const TextLine &cells) { + CompactHistoryLine *line; + line = new (blockList) CompactHistoryLine(cells, blockList); - while (lines.size() > (int) lineCount) { - delete lines.takeAt(0); - } + if (lines.size() > (int)_maxLineCount) { + delete lines.takeAt(0); + } + lines.append(line); } -bool CompactHistoryScroll::isWrappedLine ( int lineNumber ) -{ - Q_ASSERT ( lineNumber < lines.size() ); - return lines[lineNumber]->isWrapped(); +void CompactHistoryScroll::addCells(const Character a[], int count) { + TextLine newLine(count); + std::copy(a, a + count, newLine.begin()); + addCellsVector(newLine); } - -////////////////////////////////////////////////////////////////////// -// History Types -////////////////////////////////////////////////////////////////////// - -HistoryType::HistoryType() -{ +void CompactHistoryScroll::addLine(bool previousWrapped) { + CompactHistoryLine *line = lines.last(); + line->setWrapped(previousWrapped); } -HistoryType::~HistoryType() -{ +int CompactHistoryScroll::getLines() { + return lines.size(); } -////////////////////////////// - -HistoryTypeNone::HistoryTypeNone() -{ +int CompactHistoryScroll::getLineLen(int lineNumber) { + Q_ASSERT(lineNumber >= 0 && lineNumber < lines.size()); + CompactHistoryLine *line = lines[lineNumber]; + return line->getLength(); } -bool HistoryTypeNone::isEnabled() const -{ - return false; +void CompactHistoryScroll::getCells(int lineNumber, int startColumn, int count, + Character buffer[]) { + if (count == 0) + return; + Q_ASSERT(lineNumber < lines.size()); + CompactHistoryLine *line = lines[lineNumber]; + Q_ASSERT(startColumn >= 0); + Q_ASSERT((unsigned int)startColumn <= line->getLength() - count); + line->getCharacters(buffer, count, startColumn); } -HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const -{ - delete old; - return new HistoryScrollNone(); -} +void CompactHistoryScroll::setMaxNbLines(unsigned int lineCount) { + _maxLineCount = lineCount; -int HistoryTypeNone::maximumLineCount() const -{ - return 0; + while (lines.size() > (int)lineCount) { + delete lines.takeAt(0); + } } -////////////////////////////// - -HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size) - : m_size(size) -{ +bool CompactHistoryScroll::isWrappedLine(int lineNumber) { + Q_ASSERT(lineNumber < lines.size()); + return lines[lineNumber]->isWrapped(); } -bool HistoryTypeBlockArray::isEnabled() const -{ - return true; +HistoryType::HistoryType() {} +HistoryType::~HistoryType() {} +HistoryTypeNone::HistoryTypeNone() {} +bool HistoryTypeNone::isEnabled() const { return false; } +HistoryScroll *HistoryTypeNone::scroll(HistoryScroll *old) const { + delete old; + return new HistoryScrollNone(); } +int HistoryTypeNone::maximumLineCount() const { return 0; } -int HistoryTypeBlockArray::maximumLineCount() const -{ - return m_size; -} -HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const -{ - delete old; - return new HistoryScrollBlockArray(m_size); +HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size) : m_size(size) {} +bool HistoryTypeBlockArray::isEnabled() const { return true; } +int HistoryTypeBlockArray::maximumLineCount() const { return m_size; } +HistoryScroll *HistoryTypeBlockArray::scroll(HistoryScroll *old) const { + delete old; + return new HistoryScrollBlockArray(m_size); } - -////////////////////////////// - HistoryTypeBuffer::HistoryTypeBuffer(unsigned int nbLines) - : m_nbLines(nbLines) -{ -} - -bool HistoryTypeBuffer::isEnabled() const -{ - return true; -} - -int HistoryTypeBuffer::maximumLineCount() const -{ - return m_nbLines; + : m_nbLines(nbLines) {} +bool HistoryTypeBuffer::isEnabled() const { return true; } +int HistoryTypeBuffer::maximumLineCount() const { return m_nbLines; } +HistoryScroll *HistoryTypeBuffer::scroll(HistoryScroll *old) const { + if (old) { + HistoryScrollBuffer *oldBuffer = dynamic_cast(old); + if (oldBuffer) { + oldBuffer->setMaxNbLines(m_nbLines); + return oldBuffer; + } + + HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); + int lines = old->getLines(); + int startLine = 0; + if (lines > (int)m_nbLines) + startLine = lines - m_nbLines; + + Character line[LINE_SIZE]; + for (int i = startLine; i < lines; i++) { + int size = old->getLineLen(i); + if (size > LINE_SIZE) { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete[] tmp_line; + } else { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } + } + delete old; + return newScroll; + } + return new HistoryScrollBuffer(m_nbLines); } -HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const -{ - if (old) - { - HistoryScrollBuffer *oldBuffer = dynamic_cast(old); - if (oldBuffer) - { - oldBuffer->setMaxNbLines(m_nbLines); - return oldBuffer; - } +HistoryTypeFile::HistoryTypeFile(const QString &fileName) + : m_fileName(fileName) {} +bool HistoryTypeFile::isEnabled() const { return true; } +const QString &HistoryTypeFile::getFileName() const { return m_fileName; } +HistoryScroll *HistoryTypeFile::scroll(HistoryScroll *old) const { + if (dynamic_cast(old)) + return old; // Unchanged. - HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); - int lines = old->getLines(); - int startLine = 0; - if (lines > (int) m_nbLines) - startLine = lines - m_nbLines; + HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); Character line[LINE_SIZE]; - for(int i = startLine; i < lines; i++) - { - int size = old->getLineLen(i); - if (size > LINE_SIZE) - { - Character *tmp_line = new Character[size]; - old->getCells(i, 0, size, tmp_line); - newScroll->addCells(tmp_line, size); - newScroll->addLine(old->isWrappedLine(i)); - delete [] tmp_line; - } - else - { - old->getCells(i, 0, size, line); - newScroll->addCells(line, size); - newScroll->addLine(old->isWrappedLine(i)); - } + int lines = (old != nullptr) ? old->getLines() : 0; + for (int i = 0; i < lines; i++) { + int size = old->getLineLen(i); + if (size > LINE_SIZE) { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete[] tmp_line; + } else { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } } + delete old; return newScroll; - } - return new HistoryScrollBuffer(m_nbLines); } - -////////////////////////////// - -HistoryTypeFile::HistoryTypeFile(const QString& fileName) - : m_fileName(fileName) -{ -} - -bool HistoryTypeFile::isEnabled() const -{ - return true; -} - -const QString& HistoryTypeFile::getFileName() const -{ - return m_fileName; -} - -HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const -{ - if (dynamic_cast(old)) - return old; // Unchanged. - - HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); - - Character line[LINE_SIZE]; - int lines = (old != nullptr) ? old->getLines() : 0; - for(int i = 0; i < lines; i++) - { - int size = old->getLineLen(i); - if (size > LINE_SIZE) - { - Character *tmp_line = new Character[size]; - old->getCells(i, 0, size, tmp_line); - newScroll->addCells(tmp_line, size); - newScroll->addLine(old->isWrappedLine(i)); - delete [] tmp_line; - } - else - { - old->getCells(i, 0, size, line); - newScroll->addCells(line, size); - newScroll->addLine(old->isWrappedLine(i)); - } - } - - delete old; - return newScroll; -} - -int HistoryTypeFile::maximumLineCount() const -{ - return 0; -} - -////////////////////////////// - -CompactHistoryType::CompactHistoryType ( unsigned int nbLines ) - : m_nbLines ( nbLines ) -{ -} - -bool CompactHistoryType::isEnabled() const -{ - return true; -} - -int CompactHistoryType::maximumLineCount() const -{ - return m_nbLines; -} - -HistoryScroll* CompactHistoryType::scroll ( HistoryScroll *old ) const -{ - if ( old ) - { - CompactHistoryScroll *oldBuffer = dynamic_cast ( old ); - if ( oldBuffer ) - { - oldBuffer->setMaxNbLines ( m_nbLines ); - return oldBuffer; +int HistoryTypeFile::maximumLineCount() const { return 0; } + + +CompactHistoryType::CompactHistoryType(unsigned int nbLines) + : m_nbLines(nbLines) {} +bool CompactHistoryType::isEnabled() const { return true; } +int CompactHistoryType::maximumLineCount() const { return m_nbLines; } +HistoryScroll *CompactHistoryType::scroll(HistoryScroll *old) const { + if (old) { + CompactHistoryScroll *oldBuffer = dynamic_cast(old); + if (oldBuffer) { + oldBuffer->setMaxNbLines(m_nbLines); + return oldBuffer; + } + delete old; } - delete old; - } - return new CompactHistoryScroll ( m_nbLines ); + return new CompactHistoryScroll(m_nbLines); } diff --git a/lib/qtermwidget/History.h b/lib/qtermwidget/History.h index 0a3cb7d2..63f8d0d3 100644 --- a/lib/qtermwidget/History.h +++ b/lib/qtermwidget/History.h @@ -1,25 +1,24 @@ /* - This file is part of Konsole, an X terminal. - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ - -#ifndef TEHISTORY_H -#define TEHISTORY_H +#ifndef HISTORY_H +#define HISTORY_H #include #include @@ -44,37 +43,36 @@ class HistoryFile { public: - HistoryFile(); - virtual ~HistoryFile(); - - virtual void add(const unsigned char* bytes, int len); - virtual void get(unsigned char* bytes, int len, int loc); - virtual int len(); + HistoryFile(); + virtual ~HistoryFile(); - //mmaps the file in read-only mode - void map(); - //un-mmaps the file - void unmap(); - //returns true if the file is mmap'ed - bool isMapped() const; + virtual void add(const unsigned char* bytes, int len); + virtual void get(unsigned char* bytes, int len, int loc); + virtual int len(); + //mmaps the file in read-only mode + void map(); + //un-mmaps the file + void unmap(); + //returns true if the file is mmap'ed + bool isMapped() const; private: - int ion; - int length; - QTemporaryFile tmpFile; + int ion; + int length; + QTemporaryFile tmpFile; - //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed - char* fileMap; + //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed + char* fileMap; - //incremented whenever 'add' is called and decremented whenever - //'get' is called. - //this is used to detect when a large number of lines are being read and processed from the history - //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). - int readWriteBalance = 0; + //incremented whenever 'add' is called and decremented whenever + //'get' is called. + //this is used to detect when a large number of lines are being read and processed from the history + //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). + int readWriteBalance = 0; - //when readWriteBalance goes below this threshold, the file will be mmap'ed automatically - static const int MAP_THRESHOLD = -1000; + //when readWriteBalance goes below this threshold, the file will be mmap'ed automatically + static const int MAP_THRESHOLD = -1000; }; #endif @@ -84,378 +82,340 @@ class HistoryFile // Abstract base class for file and buffer versions ////////////////////////////////////////////////////////////////////// class HistoryType; - class HistoryScroll { public: - HistoryScroll(HistoryType*); - virtual ~HistoryScroll(); - - virtual bool hasScroll(); - - // access to history - virtual int getLines() = 0; - virtual int getLineLen(int lineno) = 0; - virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; - virtual bool isWrappedLine(int lineno) = 0; - - // backward compatibility (obsolete) - Character getCell(int lineno, int colno) { Character res; getCells(lineno,colno,1,&res); return res; } - - // adding lines. - virtual void addCells(const Character a[], int count) = 0; - // convenience method - this is virtual so that subclasses can take advantage - // of QVector's implicit copying - virtual void addCellsVector(const QVector& cells) - { - addCells(cells.data(),cells.size()); - } - - virtual void addLine(bool previousWrapped=false) = 0; - - // - // FIXME: Passing around constant references to HistoryType instances - // is very unsafe, because those references will no longer - // be valid if the history scroll is deleted. - // - const HistoryType& getType() const { return *m_histType; } + HistoryScroll(HistoryType*); + virtual ~HistoryScroll(); + + virtual bool hasScroll(); + + // access to history + virtual int getLines() = 0; + virtual int getLineLen(int lineno) = 0; + virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; + virtual bool isWrappedLine(int lineno) = 0; + + // backward compatibility (obsolete) + Character getCell(int lineno, int colno) { Character res; getCells(lineno,colno,1,&res); return res; } + + // adding lines. + virtual void addCells(const Character a[], int count) = 0; + // convenience method - this is virtual so that subclasses can take advantage + // of QVector's implicit copying + virtual void addCellsVector(const QVector& cells) { + addCells(cells.data(),cells.size()); + } + + virtual void addLine(bool previousWrapped=false) = 0; + + // + // FIXME: Passing around constant references to HistoryType instances + // is very unsafe, because those references will no longer + // be valid if the history scroll is deleted. + // + const HistoryType& getType() const { return *m_histType; } protected: - HistoryType* m_histType; + HistoryType* m_histType; }; #if 1 -////////////////////////////////////////////////////////////////////// -// File-based history (e.g. file log, no limitation in length) -////////////////////////////////////////////////////////////////////// - class HistoryScrollFile : public HistoryScroll { public: - HistoryScrollFile(const QString &logFileName); - ~HistoryScrollFile() override; + HistoryScrollFile(const QString &logFileName); + ~HistoryScrollFile() override; - int getLines() override; - int getLineLen(int lineno) override; - void getCells(int lineno, int colno, int count, Character res[]) override; - bool isWrappedLine(int lineno) override; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character a[], int count) override; - void addLine(bool previousWrapped=false) override; + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; private: - int startOfLine(int lineno); + int startOfLine(int lineno); - QString m_logFileName; - HistoryFile index; // lines Row(int) - HistoryFile cells; // text Row(Character) - HistoryFile lineflags; // flags Row(unsigned char) + QString m_logFileName; + HistoryFile index; // lines Row(int) + HistoryFile cells; // text Row(Character) + HistoryFile lineflags; // flags Row(unsigned char) }; -////////////////////////////////////////////////////////////////////// -// Buffer-based history (limited to a fixed nb of lines) -////////////////////////////////////////////////////////////////////// class HistoryScrollBuffer : public HistoryScroll { public: - typedef QVector HistoryLine; - - HistoryScrollBuffer(unsigned int maxNbLines = 1000); - ~HistoryScrollBuffer() override; + typedef QVector HistoryLine; - int getLines() override; - int getLineLen(int lineno) override; - void getCells(int lineno, int colno, int count, Character res[]) override; - bool isWrappedLine(int lineno) override; + HistoryScrollBuffer(unsigned int maxNbLines = 1000); + ~HistoryScrollBuffer() override; - void addCells(const Character a[], int count) override; - void addCellsVector(const QVector& cells) override; - void addLine(bool previousWrapped=false) override; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void setMaxNbLines(unsigned int nbLines); - unsigned int maxNbLines() const { return _maxLineCount; } + void addCells(const Character a[], int count) override; + void addCellsVector(const QVector& cells) override; + void addLine(bool previousWrapped=false) override; + void setMaxNbLines(unsigned int nbLines); + unsigned int maxNbLines() const { return _maxLineCount; } private: - int bufferIndex(int lineNumber) const; - - HistoryLine* _historyBuffer; - QBitArray _wrappedLine; - int _maxLineCount; - int _usedLines; - int _head; - - //QVector m_histBuffer; - //QBitArray m_wrappedLine; - //unsigned int m_maxNbLines; - //unsigned int m_nbLines; - //unsigned int m_arrayIndex; - //bool m_buffFilled; + int bufferIndex(int lineNumber) const; + + HistoryLine* _historyBuffer; + QBitArray _wrappedLine; + int _maxLineCount; + int _usedLines; + int _head; + + //QVector m_histBuffer; + //QBitArray m_wrappedLine; + //unsigned int m_maxNbLines; + //unsigned int m_nbLines; + //unsigned int m_arrayIndex; + //bool m_buffFilled; }; -/*class HistoryScrollBufferV2 : public HistoryScroll -{ -public: - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); - - virtual void addCells(const Character a[], int count); - virtual void addCells(const QVector& cells); - virtual void addLine(bool previousWrapped=false); - -};*/ - #endif -////////////////////////////////////////////////////////////////////// -// Nothing-based history (no history :-) -////////////////////////////////////////////////////////////////////// class HistoryScrollNone : public HistoryScroll { public: - HistoryScrollNone(); - ~HistoryScrollNone() override; + HistoryScrollNone(); + ~HistoryScrollNone() override; - bool hasScroll() override; + bool hasScroll() override; - int getLines() override; - int getLineLen(int lineno) override; - void getCells(int lineno, int colno, int count, Character res[]) override; - bool isWrappedLine(int lineno) override; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character a[], int count) override; - void addLine(bool previousWrapped=false) override; + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; }; -////////////////////////////////////////////////////////////////////// -// BlockArray-based history -////////////////////////////////////////////////////////////////////// class HistoryScrollBlockArray : public HistoryScroll { public: - HistoryScrollBlockArray(size_t size); - ~HistoryScrollBlockArray() override; + HistoryScrollBlockArray(size_t size); + ~HistoryScrollBlockArray() override; - int getLines() override; - int getLineLen(int lineno) override; - void getCells(int lineno, int colno, int count, Character res[]) override; - bool isWrappedLine(int lineno) override; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character a[], int count) override; - void addLine(bool previousWrapped=false) override; + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; protected: - BlockArray m_blockArray; - QHash m_lineLengths; + BlockArray m_blockArray; + QHash m_lineLengths; }; -////////////////////////////////////////////////////////////////////// -// History using compact storage -// This implementation uses a list of fixed-sized blocks -// where history lines are allocated in (avoids heap fragmentation) -////////////////////////////////////////////////////////////////////// typedef QVector TextLine; class CharacterFormat { public: - bool equalsFormat(const CharacterFormat &other) const { - return other.rendition==rendition && other.fgColor==fgColor && other.bgColor==bgColor; - } - - bool equalsFormat(const Character &c) const { - return c.rendition==rendition && c.foregroundColor==fgColor && c.backgroundColor==bgColor; - } - - void setFormat(const Character& c) { - rendition=c.rendition; - fgColor=c.foregroundColor; - bgColor=c.backgroundColor; - } - - CharacterColor fgColor, bgColor; - quint16 startPos; - quint8 rendition; + bool equalsFormat(const CharacterFormat &other) const { + return other.rendition==rendition && other.fgColor==fgColor && other.bgColor==bgColor; + } + + bool equalsFormat(const Character &c) const { + return c.rendition==rendition && c.foregroundColor==fgColor && c.backgroundColor==bgColor; + } + + void setFormat(const Character& c) { + rendition=c.rendition; + fgColor=c.foregroundColor; + bgColor=c.backgroundColor; + } + + CharacterColor fgColor, bgColor; + quint16 startPos; + quint8 rendition; }; class CompactHistoryBlock { public: - CompactHistoryBlock(){ - blockLength = 4096*64; // 256kb - -#if defined(Q_OS_WIN) - head = (quint8*) VirtualAlloc(NULL, blockLength, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - Q_ASSERT(head != NULL); -#else - head = (quint8*) mmap(nullptr, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); - Q_ASSERT(head != MAP_FAILED); -#endif - //head = (quint8*) malloc(blockLength); - tail = blockStart = head; - allocCount=0; - } - - virtual ~CompactHistoryBlock(){ - //free(blockStart); -#if defined(Q_OS_WIN) - VirtualFree((VOID *) blockStart, 0, MEM_RELEASE ); -#else - munmap(blockStart, blockLength); -#endif - } - - virtual unsigned int remaining(){ return (unsigned int)(blockStart+blockLength-tail);} - virtual unsigned int length() { return (unsigned int)(blockLength); } - virtual void* allocate(size_t length); - virtual bool contains(void *addr) {return addr>=blockStart && addr<(blockStart+blockLength);} - virtual void deallocate(); - virtual bool isInUse(){ return allocCount!=0; } ; + CompactHistoryBlock() { + blockLength = 4096*64; // 256kb + + #if defined(Q_OS_WIN) + head = (quint8*) VirtualAlloc(NULL, blockLength, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + Q_ASSERT(head != NULL); + #else + head = (quint8*) mmap(nullptr, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); + Q_ASSERT(head != MAP_FAILED); + #endif + //head = (quint8*) malloc(blockLength); + tail = blockStart = head; + allocCount=0; + } + + virtual ~CompactHistoryBlock(){ + //free(blockStart); + #if defined(Q_OS_WIN) + VirtualFree((VOID *) blockStart, 0, MEM_RELEASE ); + #else + munmap(blockStart, blockLength); + #endif + } + + virtual unsigned int remaining(){ return (unsigned int)(blockStart+blockLength-tail);} + virtual unsigned int length() { return (unsigned int)(blockLength); } + virtual void* allocate(size_t length); + virtual bool contains(void *addr) {return addr>=blockStart && addr<(blockStart+blockLength);} + virtual void deallocate(); + virtual bool isInUse(){ return allocCount!=0; } ; private: - size_t blockLength; - quint8* head; - quint8* tail; - quint8* blockStart; - int allocCount; + size_t blockLength; + quint8* head; + quint8* tail; + quint8* blockStart; + int allocCount; }; class CompactHistoryBlockList { public: - CompactHistoryBlockList() {}; - ~CompactHistoryBlockList(); + CompactHistoryBlockList() {}; + ~CompactHistoryBlockList(); - void *allocate( size_t size ); - void deallocate(void *); - int length() {return list.size();} + void *allocate( size_t size ); + void deallocate(void *); + int length() {return list.size();} private: - QList list; + QList list; }; class CompactHistoryLine { public: - CompactHistoryLine(const TextLine&, CompactHistoryBlockList& blockList); - virtual ~CompactHistoryLine(); + CompactHistoryLine(const TextLine&, CompactHistoryBlockList& blockList); + virtual ~CompactHistoryLine(); - // custom new operator to allocate memory from custom pool instead of heap - static void *operator new( size_t size, CompactHistoryBlockList& blockList); - static void operator delete( void *) { /* do nothing, deallocation from pool is done in destructor*/ } ; + // custom new operator to allocate memory from custom pool instead of heap + static void *operator new( size_t size, CompactHistoryBlockList& blockList); + static void operator delete( void *) { /* do nothing, deallocation from pool is done in destructor*/ } ; - virtual void getCharacters(Character* array, int length, int startColumn) ; - virtual void getCharacter(int index, Character &r) ; - virtual bool isWrapped() const {return wrapped;}; - virtual void setWrapped(bool isWrapped) { wrapped=isWrapped;}; - virtual unsigned int getLength() const {return length;}; + virtual void getCharacters(Character* array, int length, int startColumn) ; + virtual void getCharacter(int index, Character &r) ; + virtual bool isWrapped() const {return wrapped;}; + virtual void setWrapped(bool isWrapped) { wrapped=isWrapped;}; + virtual unsigned int getLength() const {return length;}; protected: - CompactHistoryBlockList& blockList; - CharacterFormat* formatArray; - quint16 length; - quint16* text; - quint16 formatLength; - bool wrapped; + CompactHistoryBlockList& blockList; + CharacterFormat* formatArray; + quint16 length; + quint16* text; + quint16 formatLength; + bool wrapped; }; class CompactHistoryScroll : public HistoryScroll { - typedef QList HistoryArray; + typedef QList HistoryArray; public: - CompactHistoryScroll(unsigned int maxNbLines = 1000); - ~CompactHistoryScroll() override; + CompactHistoryScroll(unsigned int maxNbLines = 1000); + ~CompactHistoryScroll() override; - int getLines() override; - int getLineLen(int lineno) override; - void getCells(int lineno, int colno, int count, Character res[]) override; - bool isWrappedLine(int lineno) override; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character a[], int count) override; - void addCellsVector(const TextLine& cells) override; - void addLine(bool previousWrapped=false) override; + void addCells(const Character a[], int count) override; + void addCellsVector(const TextLine& cells) override; + void addLine(bool previousWrapped=false) override; - void setMaxNbLines(unsigned int nbLines); - unsigned int maxNbLines() const { return _maxLineCount; } + void setMaxNbLines(unsigned int nbLines); + unsigned int maxNbLines() const { return _maxLineCount; } private: - bool hasDifferentColors(const TextLine& line) const; - HistoryArray lines; - CompactHistoryBlockList blockList; + bool hasDifferentColors(const TextLine& line) const; + HistoryArray lines; + CompactHistoryBlockList blockList; - unsigned int _maxLineCount; + unsigned int _maxLineCount; }; -////////////////////////////////////////////////////////////////////// -// History type -////////////////////////////////////////////////////////////////////// class HistoryType { public: - HistoryType(); - virtual ~HistoryType(); - - /** - * Returns true if the history is enabled ( can store lines of output ) - * or false otherwise. - */ - virtual bool isEnabled() const = 0; - /** - * Returns true if the history size is unlimited. - */ - bool isUnlimited() const { return maximumLineCount() == 0; } - /** - * Returns the maximum number of lines which this history type - * can store or 0 if the history can store an unlimited number of lines. - */ - virtual int maximumLineCount() const = 0; - - virtual HistoryScroll* scroll(HistoryScroll *) const = 0; + HistoryType(); + virtual ~HistoryType(); + + /** + * Returns true if the history is enabled ( can store lines of output ) + * or false otherwise. + */ + virtual bool isEnabled() const = 0; + /** + * Returns true if the history size is unlimited. + */ + bool isUnlimited() const { return maximumLineCount() == 0; } + /** + * Returns the maximum number of lines which this history type + * can store or 0 if the history can store an unlimited number of lines. + */ + virtual int maximumLineCount() const = 0; + + virtual HistoryScroll* scroll(HistoryScroll *) const = 0; }; class HistoryTypeNone : public HistoryType { public: - HistoryTypeNone(); + HistoryTypeNone(); - bool isEnabled() const override; - int maximumLineCount() const override; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll* scroll(HistoryScroll *) const override; + HistoryScroll* scroll(HistoryScroll *) const override; }; class HistoryTypeBlockArray : public HistoryType { public: - HistoryTypeBlockArray(size_t size); + HistoryTypeBlockArray(size_t size); - bool isEnabled() const override; - int maximumLineCount() const override; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll* scroll(HistoryScroll *) const override; + HistoryScroll* scroll(HistoryScroll *) const override; protected: - size_t m_size; + size_t m_size; }; #if 1 class HistoryTypeFile : public HistoryType { public: - HistoryTypeFile(const QString& fileName=QString()); + HistoryTypeFile(const QString& fileName=QString()); - bool isEnabled() const override; - virtual const QString& getFileName() const; - int maximumLineCount() const override; + bool isEnabled() const override; + virtual const QString& getFileName() const; + int maximumLineCount() const override; - HistoryScroll* scroll(HistoryScroll *) const override; + HistoryScroll* scroll(HistoryScroll *) const override; protected: - QString m_fileName; + QString m_fileName; }; @@ -464,12 +424,12 @@ class HistoryTypeBuffer : public HistoryType friend class HistoryScrollBuffer; public: - HistoryTypeBuffer(unsigned int nbLines); + HistoryTypeBuffer(unsigned int nbLines); - bool isEnabled() const override; - int maximumLineCount() const override; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll* scroll(HistoryScroll *) const override; + HistoryScroll* scroll(HistoryScroll *) const override; protected: unsigned int m_nbLines; @@ -478,12 +438,12 @@ class HistoryTypeBuffer : public HistoryType class CompactHistoryType : public HistoryType { public: - CompactHistoryType(unsigned int size); + CompactHistoryType(unsigned int size); - bool isEnabled() const override; - int maximumLineCount() const override; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll* scroll(HistoryScroll *) const override; + HistoryScroll* scroll(HistoryScroll *) const override; protected: unsigned int m_nbLines; @@ -492,4 +452,4 @@ class CompactHistoryType : public HistoryType #endif -#endif // TEHISTORY_H +#endif // HISTORY_H diff --git a/lib/qtermwidget/HistorySearch.cpp b/lib/qtermwidget/HistorySearch.cpp index 1a528560..337ec8ec 100644 --- a/lib/qtermwidget/HistorySearch.cpp +++ b/lib/qtermwidget/HistorySearch.cpp @@ -1,39 +1,35 @@ /* - Copyright 2013 Christian Surlykke - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2013 Christian Surlykke + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include -#include #include #include +#include -#include "TerminalCharacterDecoder.h" #include "Emulation.h" #include "HistorySearch.h" +#include "TerminalCharacterDecoder.h" -HistorySearch::HistorySearch(EmulationPtr emulation, const QRegularExpression& regExp, - bool forwards, int startColumn, int startLine, - QObject* parent) : -QObject(parent), -m_emulation(emulation), -m_regExp(regExp), -m_forwards(forwards), -m_startColumn(startColumn), -m_startLine(startLine) { +HistorySearch::HistorySearch(EmulationPtr emulation, + const QRegularExpression ®Exp, bool forwards, + int startColumn, int startLine, QObject *parent) + : QObject(parent), m_emulation(emulation), m_regExp(regExp), + m_forwards(forwards), m_startColumn(startColumn), m_startLine(startLine) { } HistorySearch::~HistorySearch() { @@ -42,18 +38,20 @@ HistorySearch::~HistorySearch() { void HistorySearch::search() { bool found = false; - if (! m_regExp.pattern().isEmpty()) - { + if (!m_regExp.pattern().isEmpty()) { if (m_forwards) { - found = search(m_startColumn, m_startLine, -1, m_emulation->lineCount()) || search(0, 0, m_startColumn, m_startLine); + found = + search(m_startColumn, m_startLine, -1, m_emulation->lineCount()) || + search(0, 0, m_startColumn, m_startLine); } else { - found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); + found = search(0, 0, m_startColumn, m_startLine) || + search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); } if (found) { - emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine); - } - else { + emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, + m_foundEndLine); + } else { emit noMatchFound(); } } @@ -61,12 +59,14 @@ void HistorySearch::search() { deleteLater(); } -bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) { +bool HistorySearch::search(int startColumn, int startLine, int endColumn, + int endLine) { int linesRead = 0; int linesToRead = endLine - startLine + 1; - // We read process history from (and including) startLine to (and including) endLine in - // blocks of at most 10K lines so that we do not use unhealthy amounts of memory + // We read process history from (and including) startLine to (and including) + // endLine in blocks of at most 10K lines so that we do not use unhealthy + // amounts of memory int blockSize; while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) { QString string; @@ -76,71 +76,72 @@ bool HistorySearch::search(int startColumn, int startLine, int endColumn, int en decoder.setRecordLinePositions(true); // Calculate lines to read and read them - int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; + int blockStartLine = m_forwards ? startLine + linesRead + : endLine - linesRead - blockSize + 1; int chunkEndLine = blockStartLine + blockSize - 1; m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine); - // We search between startColumn in the first line of the string and endColumn in the last - // line of the string. First we calculate the position (in the string) of endColumn in the - // last line of the string + // We search between startColumn in the first line of the string and + // endColumn in the last line of the string. First we calculate the position + // (in the string) of endColumn in the last line of the string int endPosition; - // The String that Emulator.writeToStream produces has a newline at the end, and so ends with an - // empty line - we ignore that. + // The String that Emulator.writeToStream produces has a newline at the end, + // and so ends with an empty line - we ignore that. int numberOfLinesInString = decoder.linePositions().size() - 1; - if (numberOfLinesInString > 0 && endColumn > -1 ) - { - endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; - } - else - { + if (numberOfLinesInString > 0 && endColumn > -1) { + endPosition = + decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; + } else { endPosition = string.size(); } - // So now we can log for m_regExp in the string between startColumn and endPosition + // So now we can log for m_regExp in the string between startColumn and + // endPosition int matchStart; QRegularExpressionMatch match; - if (m_forwards) - { + if (m_forwards) { matchStart = string.indexOf(m_regExp, startColumn, &match); - if (matchStart >= endPosition) - matchStart = -1; - } - else - { + if (matchStart >= endPosition) + matchStart = -1; + } else { matchStart = string.lastIndexOf(m_regExp, endPosition - 1, &match); if (matchStart < startColumn) matchStart = -1; } - if (matchStart > -1) - { + if (matchStart > -1) { int matchEnd = matchStart + match.capturedLength() - 1; - //qDebug() << "Found in string from" << matchStart << "to" << matchEnd; - - // Translate startPos and endPos to startColum, startLine, endColumn and endLine in history. - int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart); - m_foundStartColumn = matchStart - decoder.linePositions().at(startLineNumberInString); + // qDebug() << "Found in string from" << matchStart << "to" << matchEnd; + + // Translate startPos and endPos to startColum, startLine, endColumn and + // endLine in history. + int startLineNumberInString = + findLineNumberInString(decoder.linePositions(), matchStart); + m_foundStartColumn = + matchStart - decoder.linePositions().at(startLineNumberInString); m_foundStartLine = startLineNumberInString + startLine + linesRead; - int endLineNumberInString = findLineNumberInString(decoder.linePositions(), matchEnd); - m_foundEndColumn = matchEnd - decoder.linePositions().at(endLineNumberInString); + int endLineNumberInString = + findLineNumberInString(decoder.linePositions(), matchEnd); + m_foundEndColumn = + matchEnd - decoder.linePositions().at(endLineNumberInString); m_foundEndLine = endLineNumberInString + startLine + linesRead; return true; } - linesRead += blockSize; } return false; } - -int HistorySearch::findLineNumberInString(QList linePositions, int position) { +int HistorySearch::findLineNumberInString(QList linePositions, + int position) { int lineNum = 0; - while (lineNum + 1 < linePositions.size() && linePositions[lineNum + 1] <= position) + while (lineNum + 1 < linePositions.size() && + linePositions[lineNum + 1] <= position) lineNum++; return lineNum; diff --git a/lib/qtermwidget/HistorySearch.h b/lib/qtermwidget/HistorySearch.h index f373b6da..fa269006 100644 --- a/lib/qtermwidget/HistorySearch.h +++ b/lib/qtermwidget/HistorySearch.h @@ -1,23 +1,23 @@ /* - Copyright 2013 Christian Surlykke - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2013 Christian Surlykke + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ -#ifndef TASK_H -#define TASK_H +#ifndef HISTOTYSEARCH_H +#define HISTOTYSEARCH_H #include #include @@ -38,9 +38,7 @@ class HistorySearch : public QObject public: explicit HistorySearch(EmulationPtr emulation, const QRegularExpression& regExp, bool forwards, int startColumn, int startLine, QObject* parent); - ~HistorySearch() override; - void search(); signals: @@ -51,7 +49,6 @@ class HistorySearch : public QObject bool search(int startColumn, int startLine, int endColumn, int endLine); int findLineNumberInString(QList linePositions, int position); - EmulationPtr m_emulation; QRegularExpression m_regExp; bool m_forwards = false; @@ -64,5 +61,4 @@ class HistorySearch : public QObject int m_foundEndLine = 0; }; -#endif /* TASK_H */ - +#endif /* HISTOTYSEARCH_H */ diff --git a/lib/qtermwidget/KeyboardTranslator.cpp b/lib/qtermwidget/KeyboardTranslator.cpp index ef76d4e5..a1a5d01a 100644 --- a/lib/qtermwidget/KeyboardTranslator.cpp +++ b/lib/qtermwidget/KeyboardTranslator.cpp @@ -1,22 +1,22 @@ /* - This source file is part of Konsole, a terminal emulator. + This source file is part of Konsole, a terminal emulator. - Copyright 2007-2008 by Robert Knight + Copyright 2007-2008 by Robert Knight - 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 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. + 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "KeyboardTranslator.h" @@ -24,19 +24,19 @@ #include #include +#include #include #include -#include #include -#include -#include #include +#include +#include #include "tools.h" const QByteArray KeyboardTranslatorManager::defaultTranslatorText( -"keyboard \"Fallback Key Translator\"\n" -"key Tab : \"\\t\"" + "keyboard \"Fallback Key Translator\"\n" + "key Tab : \"\\t\"" ); #ifdef Q_OS_MAC @@ -47,20 +47,18 @@ const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::ControlModifier; #endif KeyboardTranslatorManager::KeyboardTranslatorManager() - : _haveLoadedAll(false) -{ + : _haveLoadedAll(false) { } -KeyboardTranslatorManager::~KeyboardTranslatorManager() -{ + +KeyboardTranslatorManager::~KeyboardTranslatorManager() { qDeleteAll(_translators); } -QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) -{ + +QString KeyboardTranslatorManager::findTranslatorPath(const QString &name) { return QString(get_kb_layout_dir() + name + QLatin1String(".keytab")); } -void KeyboardTranslatorManager::findTranslators() -{ +void KeyboardTranslatorManager::findTranslators() { QDir dir(get_kb_layout_dir()); QStringList filters; filters << QLatin1String("*.keytab"); @@ -71,127 +69,119 @@ void KeyboardTranslatorManager::findTranslators() // the name with a null pointer to indicate that the translator // has not yet been loaded from disk QStringListIterator listIter(list); - while (listIter.hasNext()) - { + while (listIter.hasNext()) { QString translatorPath = listIter.next(); QString name = QFileInfo(translatorPath).baseName(); - if ( !_translators.contains(name) ) - _translators.insert(name,0); + if (!_translators.contains(name)) + _translators.insert(name, 0); } - _haveLoadedAll = true; + _haveLoadedAll = true; } -const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name) -{ - if ( name.isEmpty() ) +const KeyboardTranslator * KeyboardTranslatorManager::findTranslator(const QString &name) { + if (name.isEmpty()) return defaultTranslator(); - if ( _translators.contains(name) && _translators[name] != 0 ) + if (_translators.contains(name) && _translators[name] != 0) return _translators[name]; - KeyboardTranslator* translator = loadTranslator(name); + KeyboardTranslator *translator = loadTranslator(name); - if ( translator != nullptr ) + if (translator != nullptr) _translators[name] = translator; - else if ( !name.isEmpty() ) + else if (!name.isEmpty()) qDebug() << "Unable to load translator" << name; return translator; } -bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator) -{ +bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator *translator) { Q_UNUSED(translator); return true; } -KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name) -{ - const QString& path = findTranslatorPath(name); +KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(const QString &name) { + const QString &path = findTranslatorPath(name); QFile source(path); if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) return nullptr; - return loadTranslator(&source,name); + return loadTranslator(&source, name); } -const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator() -{ +const KeyboardTranslator *KeyboardTranslatorManager::defaultTranslator() { // Try to find the default.keytab file if it exists, otherwise // fall back to the hard-coded one #if defined(Q_OS_WIN) #if defined(Q_CC_MSVC) - const KeyboardTranslator* translator = findTranslator(QLatin1String("windows_conpty")); + const KeyboardTranslator *translator = + findTranslator(QLatin1String("windows_conpty")); #else - const KeyboardTranslator* translator = findTranslator(QLatin1String("windows_winpty")); + const KeyboardTranslator *translator = + findTranslator(QLatin1String("windows_winpty")); #endif #elif defined(Q_OS_MAC) - const KeyboardTranslator* translator = findTranslator(QLatin1String("macos_default")); + const KeyboardTranslator *translator = + findTranslator(QLatin1String("macos_default")); #else - const KeyboardTranslator* translator = findTranslator(QLatin1String("linux_default")); + const KeyboardTranslator *translator = + findTranslator(QLatin1String("linux_default")); #endif - if (!translator) - { + if (!translator) { QBuffer textBuffer; textBuffer.setData(defaultTranslatorText); textBuffer.open(QIODevice::ReadOnly); - translator = loadTranslator(&textBuffer,QLatin1String("fallback")); + translator = loadTranslator(&textBuffer, QLatin1String("fallback")); } return translator; } -KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) -{ - KeyboardTranslator* translator = new KeyboardTranslator(name); +KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(QIODevice *source, const QString &name) { + KeyboardTranslator *translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); - translator->setDescription( reader.description() ); - while ( reader.hasNextEntry() ) + translator->setDescription(reader.description()); + while (reader.hasNextEntry()) translator->addEntry(reader.nextEntry()); source->close(); - if ( !reader.parseError() ) - { + if (!reader.parseError()) { return translator; - } - else - { + } else { delete translator; return nullptr; } } -KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination) -: _destination(destination) -{ - Q_ASSERT( destination && destination->isWritable() ); - +KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice *destination) + : _destination(destination) { + Q_ASSERT(destination && destination->isWritable()); _writer = new QTextStream(_destination); } -KeyboardTranslatorWriter::~KeyboardTranslatorWriter() -{ - delete _writer; + +KeyboardTranslatorWriter::~KeyboardTranslatorWriter() { + delete _writer; } -void KeyboardTranslatorWriter::writeHeader( const QString& description ) -{ + +void KeyboardTranslatorWriter::writeHeader(const QString &description) { *_writer << "keyboard \"" << description << '\"' << '\n'; } -void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) -{ + +void KeyboardTranslatorWriter::writeEntry(const KeyboardTranslator::Entry &entry) { QString result; - if ( entry.command() != KeyboardTranslator::NoCommand ) + if (entry.command() != KeyboardTranslator::NoCommand) result = entry.resultToString(); else result = QLatin1Char('\"') + entry.resultToString() + QLatin1Char('\"'); - *_writer << QLatin1String("key ") << entry.conditionToString() << QLatin1String(" : ") << result << QLatin1Char('\n'); + *_writer << QLatin1String("key ") << entry.conditionToString() + << QLatin1String(" : ") << result << QLatin1Char('\n'); } - // each line of the keyboard translation file is one of: // // - keyboard "name" @@ -199,40 +189,35 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entr // - key KeySequence : CommandName // // KeySequence begins with the name of the key ( taken from the Qt::Key enum ) -// and is followed by the keyboard modifiers and state flags ( with + or - in front -// of each modifier or flag to indicate whether it is required ). All keyboard modifiers -// and flags are optional, if a particular modifier or state is not specified it is -// assumed not to be a part of the sequence. The key sequence may contain whitespace +// and is followed by the keyboard modifiers and state flags ( with + or - in +// front of each modifier or flag to indicate whether it is required ). All +// keyboard modifiers and flags are optional, if a particular modifier or state +// is not specified it is assumed not to be a part of the sequence. The key +// sequence may contain whitespace // // eg: "key Up+Shift : scrollLineUp" // "key Next-Shift : "\E[6~" // -// (lines containing only whitespace are ignored, parseLine assumes that comments have -// already been removed) +// (lines containing only whitespace are ignored, parseLine assumes that +// comments have already been removed) // +KeyboardTranslatorReader::KeyboardTranslatorReader(QIODevice *source) + : _source(source), _hasNext(false) { + // read input until we find the description + while (_description.isEmpty() && !source->atEnd()) { + QList tokens = tokenize(QString::fromUtf8(source->readLine())); + if (!tokens.isEmpty() && tokens.first().type == Token::TitleKeyword) + _description = tokens[1].text; + } + // read first entry (if any) + readNext(); +} -KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) - : _source(source) - , _hasNext(false) -{ - // read input until we find the description - while ( _description.isEmpty() && !source->atEnd() ) - { - QList tokens = tokenize( QString::fromUtf8(source->readLine()) ); - if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) - _description = tokens[1].text; - } - // read first entry (if any) - readNext(); -} -void KeyboardTranslatorReader::readNext() -{ +void KeyboardTranslatorReader::readNext() { // find next entry - while ( !_source->atEnd() ) - { - const QList& tokens = tokenize( QString::fromUtf8(_source->readLine()) ); - if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) - { + while (!_source->atEnd()) { + const QList &tokens = tokenize(QString::fromUtf8(_source->readLine())); + if (!tokens.isEmpty() && tokens.first().type == Token::KeyKeyword) { KeyboardTranslator::States flags = KeyboardTranslator::NoState; KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; Qt::KeyboardModifiers modifiers = Qt::NoModifier; @@ -240,36 +225,28 @@ void KeyboardTranslatorReader::readNext() int keyCode = Qt::Key_unknown; - decodeSequence(tokens[1].text.toLower(), - keyCode, - modifiers, - modifierMask, - flags, - flagMask); + decodeSequence(tokens[1].text.toLower(), keyCode, modifiers, modifierMask, flags, flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; // get text or command - if ( tokens[2].type == Token::OutputText ) - { + if (tokens[2].type == Token::OutputText) { text = tokens[2].text.toLocal8Bit(); - } - else if ( tokens[2].type == Token::Command ) - { + } else if (tokens[2].type == Token::Command) { // identify command - if (!parseAsCommand(tokens[2].text,command)) + if (!parseAsCommand(tokens[2].text, command)) qDebug() << "Command" << tokens[2].text << "not understood."; } KeyboardTranslator::Entry newEntry; - newEntry.setKeyCode( keyCode ); - newEntry.setState( flags ); - newEntry.setStateMask( flagMask ); - newEntry.setModifiers( modifiers ); - newEntry.setModifierMask( modifierMask ); - newEntry.setText( text ); - newEntry.setCommand( command ); + newEntry.setKeyCode(keyCode); + newEntry.setState(flags); + newEntry.setStateMask(flagMask); + newEntry.setModifiers(modifiers); + newEntry.setModifierMask(modifierMask); + newEntry.setText(text); + newEntry.setCommand(command); _nextEntry = newEntry; @@ -282,37 +259,34 @@ void KeyboardTranslatorReader::readNext() _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) -{ - if ( text.compare(QLatin1String("erase"),Qt::CaseInsensitive) == 0 ) +bool KeyboardTranslatorReader::parseAsCommand( + const QString &text, KeyboardTranslator::Command &command) { + if (text.compare(QLatin1String("erase"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::EraseCommand; - else if ( text.compare(QLatin1String("scrollpageup"),Qt::CaseInsensitive) == 0 ) + else if (text.compare(QLatin1String("scrollpageup"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollPageUpCommand; - else if ( text.compare(QLatin1String("scrollpagedown"),Qt::CaseInsensitive) == 0 ) + else if (text.compare(QLatin1String("scrollpagedown"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollPageDownCommand; - else if ( text.compare(QLatin1String("scrolllineup"),Qt::CaseInsensitive) == 0 ) + else if (text.compare(QLatin1String("scrolllineup"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollLineUpCommand; - else if ( text.compare(QLatin1String("scrolllinedown"),Qt::CaseInsensitive) == 0 ) + else if (text.compare(QLatin1String("scrolllinedown"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollLineDownCommand; - else if ( text.compare(QLatin1String("scrolllock"),Qt::CaseInsensitive) == 0 ) + else if (text.compare(QLatin1String("scrolllock"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollLockCommand; - else if ( text.compare(QLatin1String("scrolluptotop"),Qt::CaseInsensitive) == 0) + else if (text.compare(QLatin1String("scrolluptotop"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollUpToTopCommand; - else if ( text.compare(QLatin1String("scrolldowntobottom"),Qt::CaseInsensitive) == 0) + else if (text.compare(QLatin1String("scrolldowntobottom"), Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollDownToBottomCommand; else return false; - return true; + return true; } -bool KeyboardTranslatorReader::decodeSequence(const QString& text, - int& keyCode, - Qt::KeyboardModifiers& modifiers, - Qt::KeyboardModifiers& modifierMask, - KeyboardTranslator::States& flags, - KeyboardTranslator::States& flagMask) -{ +bool KeyboardTranslatorReader::decodeSequence( + const QString &text, int &keyCode, Qt::KeyboardModifiers &modifiers, + Qt::KeyboardModifiers &modifierMask, KeyboardTranslator::States &flags, + KeyboardTranslator::States &flagMask) { bool isWanted = true; bool endOfItem = false; QString buffer; @@ -322,42 +296,32 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, KeyboardTranslator::States tempFlags = flags; KeyboardTranslator::States tempFlagMask = flagMask; - for ( int i = 0 ; i < text.size() ; i++ ) - { - const QChar& ch = text[i]; + for (int i = 0; i < text.size(); i++) { + const QChar &ch = text[i]; bool isFirstLetter = i == 0; - bool isLastLetter = ( i == text.size()-1 ); + bool isLastLetter = (i == text.size() - 1); endOfItem = true; - if ( ch.isLetterOrNumber() ) - { + if (ch.isLetterOrNumber()) { endOfItem = false; buffer.append(ch); - } else if ( isFirstLetter ) - { + } else if (isFirstLetter) { buffer.append(ch); } - if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) - { + if ((endOfItem || isLastLetter) && !buffer.isEmpty()) { Qt::KeyboardModifier itemModifier = Qt::NoModifier; int itemKeyCode = 0; KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState; - if ( parseAsModifier(buffer,itemModifier) ) - { + if (parseAsModifier(buffer, itemModifier)) { tempModifierMask |= itemModifier; - - if ( isWanted ) + if (isWanted) tempModifiers |= itemModifier; - } - else if ( parseAsStateFlag(buffer,itemFlag) ) - { + } else if (parseAsStateFlag(buffer, itemFlag)) { tempFlagMask |= itemFlag; - - if ( isWanted ) + if (isWanted) tempFlags |= itemFlag; - } - else if ( parseAsKeyCode(buffer,itemKeyCode) ) + } else if (parseAsKeyCode(buffer, itemKeyCode)) keyCode = itemKeyCode; else qDebug() << "Unable to parse key binding item:" << buffer; @@ -367,10 +331,10 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, // check if this is a wanted / not-wanted flag and update the // state ready for the next item - if ( ch == QLatin1Char('+') ) - isWanted = true; - else if ( ch == QLatin1Char('-') ) - isWanted = false; + if (ch == QLatin1Char('+')) + isWanted = true; + else if (ch == QLatin1Char('-')) + isWanted = false; } modifiers = tempModifiers; @@ -381,58 +345,56 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, return true; } -bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) -{ - if ( item == QLatin1String("shift") ) +bool KeyboardTranslatorReader::parseAsModifier(const QString &item, + Qt::KeyboardModifier &modifier) { + if (item == QLatin1String("shift")) modifier = Qt::ShiftModifier; - else if ( item == QLatin1String("ctrl") || item == QLatin1String("control") ) + else if (item == QLatin1String("ctrl") || item == QLatin1String("control")) modifier = Qt::ControlModifier; - else if ( item == QLatin1String("alt") ) + else if (item == QLatin1String("alt")) modifier = Qt::AltModifier; - else if ( item == QLatin1String("meta") ) + else if (item == QLatin1String("meta")) modifier = Qt::MetaModifier; - else if ( item == QLatin1String("keypad") ) + else if (item == QLatin1String("keypad")) modifier = Qt::KeypadModifier; else return false; return true; } -bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) -{ - if ( item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys") ) + +bool KeyboardTranslatorReader::parseAsStateFlag(const QString &item, KeyboardTranslator::State &flag) { + if (item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys")) flag = KeyboardTranslator::CursorKeysState; - else if ( item == QLatin1String("ansi") ) + else if (item == QLatin1String("ansi")) flag = KeyboardTranslator::AnsiState; - else if ( item == QLatin1String("newline") ) + else if (item == QLatin1String("newline")) flag = KeyboardTranslator::NewLineState; - else if ( item == QLatin1String("appscreen") ) + else if (item == QLatin1String("appscreen")) flag = KeyboardTranslator::AlternateScreenState; - else if ( item == QLatin1String("anymod") || item == QLatin1String("anymodifier") ) + else if (item == QLatin1String("anymod") || item == QLatin1String("anymodifier")) flag = KeyboardTranslator::AnyModifierState; - else if ( item == QLatin1String("appkeypad") ) + else if (item == QLatin1String("appkeypad")) flag = KeyboardTranslator::ApplicationKeypadState; else return false; return true; } -bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode) -{ + +bool KeyboardTranslatorReader::parseAsKeyCode(const QString &item, int &keyCode) { QKeySequence sequence = QKeySequence::fromString(item); - if ( !sequence.isEmpty() ) - { + if (!sequence.isEmpty()) { keyCode = sequence[0].toCombined(); - if ( sequence.count() > 1 ) - { + if (sequence.count() > 1) { qDebug() << "Unhandled key codes in sequence: " << item; } } // additional cases implemented for backwards compatibility with KDE 3 - else if ( item == QLatin1String("prior") ) + else if (item == QLatin1String("prior")) keyCode = Qt::Key_PageUp; - else if ( item == QLatin1String("next") ) + else if (item == QLatin1String("next")) keyCode = Qt::Key_PageDown; else return false; @@ -440,26 +402,25 @@ bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode return true; } -QString KeyboardTranslatorReader::description() const -{ +QString KeyboardTranslatorReader::description() const { return _description; } -bool KeyboardTranslatorReader::hasNextEntry() const -{ - return _hasNext; + +bool KeyboardTranslatorReader::hasNextEntry() const { + return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , - const QString& result ) -{ + +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry(const QString &condition, + const QString &result) { QString entryString = QString::fromLatin1("keyboard \"temporary\"\nkey "); entryString.append(condition); entryString.append(QLatin1String(" : ")); - // if 'result' is the name of a command then the entry result will be that command, - // otherwise the result will be treated as a string to echo when the key sequence - // specified by 'condition' is pressed + // if 'result' is the name of a command then the entry result will be that + // command, otherwise the result will be treated as a string to echo when the + // key sequence specified by 'condition' is pressed KeyboardTranslator::Command command; - if (parseAsCommand(result,command)) + if (parseAsCommand(result, command)) entryString.append(result); else entryString.append(QLatin1Char('\"') + result + QLatin1Char('\"')); @@ -470,32 +431,30 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& KeyboardTranslatorReader reader(&buffer); KeyboardTranslator::Entry entry; - if ( reader.hasNextEntry() ) + if (reader.hasNextEntry()) entry = reader.nextEntry(); return entry; } -KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() -{ - Q_ASSERT( _hasNext ); +KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() { + Q_ASSERT(_hasNext); KeyboardTranslator::Entry entry = _nextEntry; readNext(); return entry; } -bool KeyboardTranslatorReader::parseError() -{ - return false; + +bool KeyboardTranslatorReader::parseError() { + return false; } -QList KeyboardTranslatorReader::tokenize(const QString& line) -{ + +QList KeyboardTranslatorReader::tokenize(const QString &line) { QString text = line; // remove comments bool inQuotes = false; int commentPos = -1; - for (int i=text.length()-1;i>=0;i--) - { + for (int i = text.length() - 1; i >= 0; i--) { QChar ch = text[i]; if (ch == QLatin1Char('\"')) inQuotes = !inQuotes; @@ -503,7 +462,7 @@ QList KeyboardTranslatorReader::tokenize(const commentPos = i; } if (commentPos != -1) - text.remove(commentPos,text.length()); + text.remove(commentPos, text.length()); text = text.simplified(); @@ -511,56 +470,48 @@ QList KeyboardTranslatorReader::tokenize(const static QRegularExpression title(QLatin1String("keyboard\\s+\"(.*)\"")); // key line: key KeySequence : "output" // key line: key KeySequence : command - static QRegularExpression key(QLatin1String("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)")); + static QRegularExpression key( + QLatin1String("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)")); QList list; - if ( text.isEmpty() ) - { + if (text.isEmpty()) { return list; } const auto titleMatch = title.match(text); const auto keyMatch = key.match(text); - if ( titleMatch.hasMatch() ) - { - Token titleToken = { Token::TitleKeyword , QString() }; - Token textToken = { Token::TitleText , titleMatch.captured(1) }; + if (titleMatch.hasMatch()) { + Token titleToken = {Token::TitleKeyword, QString()}; + Token textToken = {Token::TitleText, titleMatch.captured(1)}; list << titleToken << textToken; - } - else if ( keyMatch.hasMatch() ) - { - Token keyToken = { Token::KeyKeyword , QString() }; - Token sequenceToken = { Token::KeySequence , keyMatch.captured(1).remove(QLatin1Char(' ')) }; + } else if (keyMatch.hasMatch()) { + Token keyToken = {Token::KeyKeyword, QString()}; + Token sequenceToken = {Token::KeySequence, + keyMatch.captured(1).remove(QLatin1Char(' '))}; list << keyToken << sequenceToken; - if ( keyMatch.captured(3).isEmpty() ) - { + if (keyMatch.captured(3).isEmpty()) { // capturedTexts()[2] is a command - Token commandToken = { Token::Command , keyMatch.captured(2) }; + Token commandToken = {Token::Command, keyMatch.captured(2)}; list << commandToken; - } - else - { + } else { // capturedTexts()[3] is the output string - Token outputToken = { Token::OutputText , keyMatch.captured(3) }; - list << outputToken; + Token outputToken = {Token::OutputText, keyMatch.captured(3)}; + list << outputToken; } - } - else - { - qDebug() << "Line in keyboard translator file could not be understood:" << text; + } else { + qDebug() << "Line in keyboard translator file could not be understood:" + << text; } return list; } -QList KeyboardTranslatorManager::allTranslators() -{ - if ( !_haveLoadedAll ) - { +QList KeyboardTranslatorManager::allTranslators() { + if (!_haveLoadedAll) { findTranslators(); } @@ -568,210 +519,220 @@ QList KeyboardTranslatorManager::allTranslators() } KeyboardTranslator::Entry::Entry() -: _keyCode(0) -, _modifiers(Qt::NoModifier) -, _modifierMask(Qt::NoModifier) -, _state(NoState) -, _stateMask(NoState) -, _command(NoCommand) -{ -} - -bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const -{ - return _keyCode == rhs._keyCode && - _modifiers == rhs._modifiers && - _modifierMask == rhs._modifierMask && - _state == rhs._state && - _stateMask == rhs._stateMask && - _command == rhs._command && - _text == rhs._text; -} - -bool KeyboardTranslator::Entry::matches(int keyCode , + : _keyCode(0), _modifiers(Qt::NoModifier), _modifierMask(Qt::NoModifier), + _state(NoState), _stateMask(NoState), _command(NoCommand) { +} + +bool KeyboardTranslator::Entry::operator==(const Entry &rhs) const { + return _keyCode == rhs._keyCode && _modifiers == rhs._modifiers && + _modifierMask == rhs._modifierMask && _state == rhs._state && + _stateMask == rhs._stateMask && _command == rhs._command && + _text == rhs._text; +} + +bool KeyboardTranslator::Entry::matches(int keyCode, Qt::KeyboardModifiers modifiers, - States testState) const -{ + States testState) const { #ifdef Q_OS_MAC // On Mac, arrow keys are considered part of keypad. Ignore that. modifiers &= ~Qt::KeypadModifier; #endif - if ( _keyCode != keyCode ) + if (_keyCode != keyCode) return false; - if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) + if ((modifiers & _modifierMask) != (_modifiers & _modifierMask)) return false; // if modifiers is non-zero, the 'any modifier' state is implicit - if ( (modifiers & ~Qt::KeypadModifier) != 0 ) + if ((modifiers & ~Qt::KeypadModifier) != 0) testState |= AnyModifierState; - if ( (testState & _stateMask) != (_state & _stateMask) ) + if ((testState & _stateMask) != (_state & _stateMask)) return false; - // special handling for the 'Any Modifier' state, which checks for the presence of - // any or no modifiers. In this context, the 'keypad' modifier does not count. + // special handling for the 'Any Modifier' state, which checks for the + // presence of any or no modifiers. In this context, the 'keypad' modifier + // does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; - if ( _stateMask & KeyboardTranslator::AnyModifierState ) - { - if ( wantAnyModifier != anyModifiersSet ) - return false; + if (_stateMask & KeyboardTranslator::AnyModifierState) { + if (wantAnyModifier != anyModifiersSet) + return false; } return true; } -QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const -{ - QByteArray result(text(expandWildCards,modifiers)); - for ( int i = 0 ; i < result.size() ; i++ ) - { +QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards, + Qt::KeyboardModifiers modifiers) const { + QByteArray result(text(expandWildCards, modifiers)); + + for (int i = 0; i < result.size(); i++) { char ch = result[i]; char replacement = 0; - switch ( ch ) - { - case 27 : replacement = 'E'; break; - case 8 : replacement = 'b'; break; - case 12 : replacement = 'f'; break; - case 9 : replacement = 't'; break; - case 13 : replacement = 'r'; break; - case 10 : replacement = 'n'; break; + switch (ch) { + case 27: + replacement = 'E'; + break; + case 8: + replacement = 'b'; + break; + case 12: + replacement = 'f'; + break; + case 9: + replacement = 't'; + break; + case 13: + replacement = 'r'; + break; + case 10: + replacement = 'n'; + break; default: // any character which is not printable is replaced by an equivalent // \xhh escape sequence (where 'hh' are the corresponding hex digits) - if ( !QChar(QLatin1Char(ch)).isPrint() ) + if (!QChar(QLatin1Char(ch)).isPrint()) replacement = 'x'; + break; } - if ( replacement == 'x' ) - { + if (replacement == 'x') { QByteArray escaped("\\x"); - escaped += QByteArray(1,ch).toHex(); + escaped += QByteArray(1, ch).toHex(); result.replace(i, 1, QByteArrayView(escaped)); - } else if ( replacement != 0 ) - { - result.remove(i,1); - result.insert(i,'\\'); - result.insert(i+1,replacement); + } else if (replacement != 0) { + result.remove(i, 1); + result.insert(i, '\\'); + result.insert(i + 1, replacement); } } return result; } -QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const -{ + +QByteArray KeyboardTranslator::Entry::unescape(const QByteArray &input) const { QByteArray result(input); - for ( int i = 0 ; i < result.size()-1 ; i++ ) - { + for (int i = 0; i < result.size() - 1; i++) { char ch = result[i]; - if ( ch == '\\' ) - { - char replacement[2] = {0,0}; - int charsToRemove = 2; - bool escapedChar = true; - - switch ( result[i+1] ) - { - case 'E' : replacement[0] = 27; break; - case 'b' : replacement[0] = 8 ; break; - case 'f' : replacement[0] = 12; break; - case 't' : replacement[0] = 9 ; break; - case 'r' : replacement[0] = 13; break; - case 'n' : replacement[0] = 10; break; - case 'x' : - { + if (ch == '\\') { + char replacement[2] = {0, 0}; + int charsToRemove = 2; + bool escapedChar = true; + + switch (result[i + 1]) { + case 'E': + replacement[0] = 27; + break; + case 'b': + replacement[0] = 8; + break; + case 'f': + replacement[0] = 12; + break; + case 't': + replacement[0] = 9; + break; + case 'r': + replacement[0] = 13; + break; + case 'n': + replacement[0] = 10; + break; + case 'x': { // format is \xh or \xhh where 'h' is a hexadecimal // digit from 0-9 or A-F which should be replaced // with the corresponding character value char hexDigits[3] = {0}; - if ( (i < result.size()-2) && isxdigit(result[i+2]) ) - hexDigits[0] = result[i+2]; - if ( (i < result.size()-3) && isxdigit(result[i+3]) ) - hexDigits[1] = result[i+3]; + if ((i < result.size() - 2) && isxdigit(result[i + 2])) + hexDigits[0] = result[i + 2]; + if ((i < result.size() - 3) && isxdigit(result[i + 3])) + hexDigits[1] = result[i + 3]; unsigned charValue = 0; - sscanf(hexDigits,"%x",&charValue); + sscanf(hexDigits, "%x", &charValue); replacement[0] = (char)charValue; charsToRemove = 2 + strlen(hexDigits); - } - break; - default: - escapedChar = false; - } - - if ( escapedChar ) - result.replace(i,charsToRemove,replacement); + break; + } + default: + escapedChar = false; + break; + } + + if (escapedChar) + result.replace(i, charsToRemove, replacement); } } return result; } -void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const -{ - if ( !(modifier & _modifierMask) ) +void KeyboardTranslator::Entry::insertModifier(QString &item, + int modifier) const { + if (!(modifier & _modifierMask)) return; - if ( modifier & _modifiers ) + if (modifier & _modifiers) item += QLatin1Char('+'); else item += QLatin1Char('-'); - if ( modifier == Qt::ShiftModifier ) + if (modifier == Qt::ShiftModifier) item += QLatin1String("Shift"); - else if ( modifier == Qt::ControlModifier ) + else if (modifier == Qt::ControlModifier) item += QLatin1String("Ctrl"); - else if ( modifier == Qt::AltModifier ) + else if (modifier == Qt::AltModifier) item += QLatin1String("Alt"); - else if ( modifier == Qt::MetaModifier ) + else if (modifier == Qt::MetaModifier) item += QLatin1String("Meta"); - else if ( modifier == Qt::KeypadModifier ) + else if (modifier == Qt::KeypadModifier) item += QLatin1String("KeyPad"); } -void KeyboardTranslator::Entry::insertState( QString& item , int state ) const -{ - if ( !(state & _stateMask) ) + +void KeyboardTranslator::Entry::insertState(QString &item, int state) const { + if (!(state & _stateMask)) return; - if ( state & _state ) - item += QLatin1Char('+') ; + if (state & _state) + item += QLatin1Char('+'); else - item += QLatin1Char('-') ; + item += QLatin1Char('-'); - if ( state == KeyboardTranslator::AlternateScreenState ) + if (state == KeyboardTranslator::AlternateScreenState) item += QLatin1String("AppScreen"); - else if ( state == KeyboardTranslator::NewLineState ) + else if (state == KeyboardTranslator::NewLineState) item += QLatin1String("NewLine"); - else if ( state == KeyboardTranslator::AnsiState ) + else if (state == KeyboardTranslator::AnsiState) item += QLatin1String("Ansi"); - else if ( state == KeyboardTranslator::CursorKeysState ) + else if (state == KeyboardTranslator::CursorKeysState) item += QLatin1String("AppCursorKeys"); - else if ( state == KeyboardTranslator::AnyModifierState ) + else if (state == KeyboardTranslator::AnyModifierState) item += QLatin1String("AnyModifier"); - else if ( state == KeyboardTranslator::ApplicationKeypadState ) + else if (state == KeyboardTranslator::ApplicationKeypadState) item += QLatin1String("AppKeypad"); } -QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const -{ - if ( !_text.isEmpty() ) - return QString::fromLatin1(escapedText(expandWildCards,modifiers)); - else if ( _command == EraseCommand ) + +QString KeyboardTranslator::Entry::resultToString( + bool expandWildCards, Qt::KeyboardModifiers modifiers) const { + if (!_text.isEmpty()) + return QString::fromLatin1(escapedText(expandWildCards, modifiers)); + else if (_command == EraseCommand) return QLatin1String("Erase"); - else if ( _command == ScrollPageUpCommand ) + else if (_command == ScrollPageUpCommand) return QLatin1String("ScrollPageUp"); - else if ( _command == ScrollPageDownCommand ) + else if (_command == ScrollPageDownCommand) return QLatin1String("ScrollPageDown"); - else if ( _command == ScrollLineUpCommand ) + else if (_command == ScrollLineUpCommand) return QLatin1String("ScrollLineUp"); - else if ( _command == ScrollLineDownCommand ) + else if (_command == ScrollLineDownCommand) return QLatin1String("ScrollLineDown"); - else if ( _command == ScrollLockCommand ) + else if (_command == ScrollLockCommand) return QLatin1String("ScrollLock"); else if (_command == ScrollUpToTopCommand) return QLatin1String("ScrollUpToTop"); @@ -780,105 +741,98 @@ QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::Keybo return QString(); } -QString KeyboardTranslator::Entry::conditionToString() const -{ + +QString KeyboardTranslator::Entry::conditionToString() const { QString result = QKeySequence(_keyCode).toString(); - insertModifier( result , Qt::ShiftModifier ); - insertModifier( result , Qt::ControlModifier ); - insertModifier( result , Qt::AltModifier ); - insertModifier( result , Qt::MetaModifier ); - insertModifier( result , Qt::KeypadModifier ); + insertModifier(result, Qt::ShiftModifier); + insertModifier(result, Qt::ControlModifier); + insertModifier(result, Qt::AltModifier); + insertModifier(result, Qt::MetaModifier); + insertModifier(result, Qt::KeypadModifier); - insertState( result , KeyboardTranslator::AlternateScreenState ); - insertState( result , KeyboardTranslator::NewLineState ); - insertState( result , KeyboardTranslator::AnsiState ); - insertState( result , KeyboardTranslator::CursorKeysState ); - insertState( result , KeyboardTranslator::AnyModifierState ); - insertState( result , KeyboardTranslator::ApplicationKeypadState ); + insertState(result, KeyboardTranslator::AlternateScreenState); + insertState(result, KeyboardTranslator::NewLineState); + insertState(result, KeyboardTranslator::AnsiState); + insertState(result, KeyboardTranslator::CursorKeysState); + insertState(result, KeyboardTranslator::AnyModifierState); + insertState(result, KeyboardTranslator::ApplicationKeypadState); return result; } -KeyboardTranslator::KeyboardTranslator(const QString& name) -: _name(name) -{ +KeyboardTranslator::KeyboardTranslator(const QString &name) : _name(name) { } -void KeyboardTranslator::setDescription(const QString& description) -{ +void KeyboardTranslator::setDescription(const QString &description) { _description = description; } -QString KeyboardTranslator::description() const -{ - return _description; + +QString KeyboardTranslator::description() const { + return _description; } -void KeyboardTranslator::setName(const QString& name) -{ - _name = name; + +void KeyboardTranslator::setName(const QString &name) { + _name = name; } -QString KeyboardTranslator::name() const -{ - return _name; + +QString KeyboardTranslator::name() const { + return _name; } -QList KeyboardTranslator::entries() const -{ +QList KeyboardTranslator::entries() const { return _entries.values(); } -void KeyboardTranslator::addEntry(const Entry& entry) -{ +void KeyboardTranslator::addEntry(const Entry &entry) { const int keyCode = entry.keyCode(); - _entries.insert(keyCode,entry); -} -void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) -{ - if ( !existing.isNull() ) - _entries.remove(existing.keyCode(),existing); - _entries.insert(replacement.keyCode(),replacement); -} -void KeyboardTranslator::removeEntry(const Entry& entry) -{ - _entries.remove(entry.keyCode(),entry); -} -KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const -{ - for (auto it = _entries.cbegin(), end = _entries.cend(); it != end; ++it) - { + _entries.insert(keyCode, entry); +} + +void KeyboardTranslator::replaceEntry(const Entry &existing, + const Entry &replacement) { + if (!existing.isNull()) + _entries.remove(existing.keyCode(), existing); + _entries.insert(replacement.keyCode(), replacement); +} + +void KeyboardTranslator::removeEntry(const Entry &entry) { + _entries.remove(entry.keyCode(), entry); +} + +KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, + States state) const { + for (auto it = _entries.cbegin(), end = _entries.cend(); it != end; ++it) { if (it.key() == keyCode) - if ( it.value().matches(keyCode,modifiers,state) ) + if (it.value().matches(keyCode, modifiers, state)) return *it; } return Entry(); // entry not found } -void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) -{ - _translators.insert(translator->name(),translator); - if ( !saveTranslator(translator) ) - qDebug() << "Unable to save translator" << translator->name() - << "to disk."; +void KeyboardTranslatorManager::addTranslator(KeyboardTranslator *translator) { + _translators.insert(translator->name(), translator); + + if (!saveTranslator(translator)) + qDebug() << "Unable to save translator" << translator->name() << "to disk."; } -bool KeyboardTranslatorManager::deleteTranslator(const QString& name) -{ - Q_ASSERT( _translators.contains(name) ); + +bool KeyboardTranslatorManager::deleteTranslator(const QString &name) { + Q_ASSERT(_translators.contains(name)); // locate and delete QString path = findTranslatorPath(name); - if ( QFile::remove(path) ) - { + if (QFile::remove(path)) { _translators.remove(name); return true; - } - else - { + } else { qDebug() << "Failed to remove translator - " << path; return false; } } -Q_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) -KeyboardTranslatorManager* KeyboardTranslatorManager::instance() -{ + +Q_GLOBAL_STATIC(KeyboardTranslatorManager, theKeyboardTranslatorManager) + +KeyboardTranslatorManager *KeyboardTranslatorManager::instance() { return theKeyboardTranslatorManager; } diff --git a/lib/qtermwidget/KeyboardTranslator.h b/lib/qtermwidget/KeyboardTranslator.h index 7f650fbf..e48a7b0c 100644 --- a/lib/qtermwidget/KeyboardTranslator.h +++ b/lib/qtermwidget/KeyboardTranslator.h @@ -1,22 +1,22 @@ /* - This source file is part of Konsole, a terminal emulator. + This source file is part of Konsole, a terminal emulator. - Copyright 2007-2008 by Robert Knight + Copyright 2007-2008 by Robert Knight - 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 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. + 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef KEYBOARDTRANSLATOR_H #define KEYBOARDTRANSLATOR_H @@ -54,8 +54,7 @@ class KeyboardTranslator * This enum describes the states which may be associated with with a particular * entry in the keyboard translation entry. */ - enum State - { + enum State { /** Indicates that no special state is active */ NoState = 0, /** @@ -86,8 +85,7 @@ class KeyboardTranslator /** * This enum describes commands which are associated with particular key sequences. */ - enum Command - { + enum Command { /** Indicates that no command is associated with this command sequence */ NoCommand = 0, /** TODO Document me */ @@ -116,8 +114,7 @@ class KeyboardTranslator * and the character sequence and commands associated with it for a particular * KeyboardTranslator. */ - class Entry - { + class Entry { public: /** * Constructs a new entry for a keyboard translator. @@ -378,10 +375,8 @@ class KeyboardTranslatorReader static KeyboardTranslator::Entry createEntry( const QString& condition , const QString& result ); private: - struct Token - { - enum Type - { + struct Token { + enum Type { TitleKeyword, TitleText, KeyKeyword, @@ -404,7 +399,7 @@ class KeyboardTranslatorReader static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier); static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state); static bool parseAsKeyCode(const QString& item , int& keyCode); - static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); + static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); QIODevice* _source; QString _description; @@ -497,7 +492,7 @@ class KeyboardTranslatorManager QList allTranslators(); /** Returns the global KeyboardTranslatorManager instance. */ - static KeyboardTranslatorManager* instance(); + static KeyboardTranslatorManager* instance(); private: static const QByteArray defaultTranslatorText; @@ -515,53 +510,60 @@ class KeyboardTranslatorManager bool _haveLoadedAll; }; -inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } -inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; } +inline int KeyboardTranslator::Entry::keyCode() const { + return _keyCode; +} -inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) -{ +inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { + _keyCode = keyCode; +} + +inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) { _modifiers = modifier; } -inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } -inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) -{ +inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { + return _modifiers; +} + +inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) { _modifierMask = mask; } -inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } -inline bool KeyboardTranslator::Entry::isNull() const -{ +inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { + return _modifierMask; +} + +inline bool KeyboardTranslator::Entry::isNull() const { return ( *this == Entry() ); } -inline void KeyboardTranslator::Entry::setCommand( Command command ) -{ +inline void KeyboardTranslator::Entry::setCommand( Command command ) { _command = command; } -inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; } -inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) -{ +inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { + return _command; +} + +inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) { _text = unescape(text); } -inline int oneOrZero(int value) -{ + +inline int oneOrZero(int value) { return value ? 1 : 0; } -inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const -{ + +inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray expandedText = _text; - if (expandWildCards) - { + if (expandWildCards) { int modifierValue = 1; modifierValue += oneOrZero(modifiers & Qt::ShiftModifier); modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; modifierValue += oneOrZero(modifiers & KeyboardTranslator::CTRL_MOD) << 2; - for (int i=0;i<_text.length();i++) - { + for (int i=0;i<_text.length();i++) { if (expandedText[i] == '*') expandedText[i] = '0' + modifierValue; } @@ -570,17 +572,21 @@ inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::Keybo return expandedText; } -inline void KeyboardTranslator::Entry::setState( States state ) -{ +inline void KeyboardTranslator::Entry::setState( States state ) { _state = state; } -inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } -inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) -{ +inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { + return _state; +} + +inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) { _stateMask = stateMask; } -inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } + +inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { + return _stateMask; +} Q_DECLARE_METATYPE(KeyboardTranslator::Entry) Q_DECLARE_METATYPE(const KeyboardTranslator*) diff --git a/lib/qtermwidget/LineFont.h b/lib/qtermwidget/LineFont.h deleted file mode 100644 index 9c080ea2..00000000 --- a/lib/qtermwidget/LineFont.h +++ /dev/null @@ -1,21 +0,0 @@ -// WARNING: Autogenerated by "fontembedder ./linefont.src". -// You probably do not want to hand-edit this! - -static const quint32 LineChars[] = { - 0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, - 0x00421c00, 0x00439ce0, 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, - 0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, 0x004279ce, 0x00e77884, - 0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, - 0x00e73dce, 0x0047bdee, 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, - 0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, 0x000e7f84, 0x000fffe4, - 0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, - 0x00427dce, 0x00e77c84, 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, - 0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, - 0x000e1384, 0x0000794a, 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, - 0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, 0x00ad83e0, 0x000f83e4, - 0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, - 0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, 0x0003fce0, 0x004239ce -}; diff --git a/lib/qtermwidget/Screen.cpp b/lib/qtermwidget/Screen.cpp index cf406feb..74774a3d 100644 --- a/lib/qtermwidget/Screen.cpp +++ b/lib/qtermwidget/Screen.cpp @@ -1,120 +1,102 @@ /* - This file is part of Konsole, an X terminal. - - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. - */ + This file is part of Konsole, an X terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ #include "Screen.h" +#include #include #include #include -#include -#include #include +#include #include "CharWidth.h" #include "TerminalCharacterDecoder.h" -//Macro to convert x,y position on screen to position within an image. +// Macro to convert x,y position on screen to position within an image. // -//Originally the image was stored as one large contiguous block of -//memory, so a position within the image could be represented as an -//offset from the beginning of the block. For efficiency reasons this -//is no longer the case. -//Many internal parts of this class still use this representation for parameters and so on, -//notably moveImage() and clearImage(). -//This macro converts from an X,Y position into an image offset. +// Originally the image was stored as one large contiguous block of +// memory, so a position within the image could be represented as an +// offset from the beginning of the block. For efficiency reasons this +// is no longer the case. +// Many internal parts of this class still use this representation for +// parameters and so on, notably moveImage() and clearImage(). This macro +// converts from an X,Y position into an image offset. #ifndef loc -#define loc(X,Y) ((Y)*columns+(X)) +#define loc(X, Y) ((Y) * columns + (X)) #endif +Character Screen::defaultChar = Character( + ' ', CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), + CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), DEFAULT_RENDITION); + +// #define REVERSE_WRAPPED_LINES // for wrapped line debug -Character Screen::defaultChar = Character(' ', - CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), - CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), - DEFAULT_RENDITION); - -//#define REVERSE_WRAPPED_LINES // for wrapped line debug - - Screen::Screen(int l, int c) -: lines(l), - columns(c), - screenLines(new ImageLine[lines+1] ), - _scrolledLines(0), - _droppedLines(0), - history(new HistoryScrollNone()), - cuX(0), cuY(0), - currentRendition(0), - _topMargin(0), _bottomMargin(0), - selBegin(0), selTopLeft(0), selBottomRight(0), - blockSelectionMode(false), - effectiveForeground(CharacterColor()), effectiveBackground(CharacterColor()), effectiveRendition(0), - lastPos(-1) -{ - lineProperties.resize(lines+1); - for (int i=0;i _bottomMargin ? lines-1 : _bottomMargin; - cuX = qMin(columns-1,cuX); // nowrap! - cuY = qMin(stop,cuY+n); +void Screen::cursorDown(int n) { + if (n == 0) + n = 1; // Default + int stop = cuY > _bottomMargin ? lines - 1 : _bottomMargin; + cuX = qMin(columns - 1, cuX); // nowrap! + cuY = qMin(stop, cuY + n); } -void Screen::cursorLeft(int n) - //=CUB -{ - if (n == 0) n = 1; // Default - cuX = qMin(columns-1,cuX); // nowrap! - cuX = qMax(0,cuX-n); +void Screen::cursorLeft(int n) { + if (n == 0) + n = 1; // Default + cuX = qMin(columns - 1, cuX); // nowrap! + cuX = qMax(0, cuX - n); } -void Screen::cursorNextLine(int n) - //=CNL -{ +void Screen::cursorNextLine(int n) { if (n == 0) { n = 1; // Default } @@ -127,38 +109,36 @@ void Screen::cursorNextLine(int n) } } -void Screen::cursorPreviousLine(int n) - //=CPL -{ +void Screen::cursorPreviousLine(int n) { if (n == 0) { n = 1; // Default } cuX = 0; while (n > 0) { - if (cuY > 0) { + if (cuY > 0) { cuY -= 1; } n--; } } -void Screen::cursorRight(int n) - //=CUF -{ - if (n == 0) n = 1; // Default - cuX = qMin(columns-1,cuX+n); -} - -void Screen::setMargins(int top, int bot) - //=STBM -{ - if (top == 0) top = 1; // Default - if (bot == 0) bot = lines; // Default - top = top - 1; // Adjust to internal lineno - bot = bot - 1; // Adjust to internal lineno - if ( !( 0 <= top && top < bot && bot < lines ) ) - { //Debug()<<" setRegion("< 0) cuY -= 1; } -void Screen::nextLine() - //=NEL -{ - toStartOfLine(); index(); +void Screen::nextLine() { + toStartOfLine(); + index(); } -void Screen::eraseChars(int n) -{ - if (n == 0) n = 1; // Default - int p = qMax(0,qMin(cuX+n-1,columns-1)); - clearImage(loc(cuX,cuY),loc(p,cuY),' '); +void Screen::eraseChars(int n) { + if (n == 0) + n = 1; // Default + int p = qMax(0, qMin(cuX + n - 1, columns - 1)); + clearImage(loc(cuX, cuY), loc(p, cuY), ' '); } -void Screen::deleteChars(int n) -{ - Q_ASSERT( n >= 0 ); +void Screen::deleteChars(int n) { + Q_ASSERT(n >= 0); // always delete at least one char if (n == 0) n = 1; // if cursor is beyond the end of the line there is nothing to do - if ( cuX >= screenLines[cuY].count() ) + if (cuX >= screenLines[cuY].count()) return; - if ( cuX+n > screenLines[cuY].count() ) + if (cuX + n > screenLines[cuY].count()) n = screenLines[cuY].count() - cuX; - Q_ASSERT( n >= 0 ); - Q_ASSERT( cuX+n <= screenLines[cuY].count() ); + Q_ASSERT(n >= 0); + Q_ASSERT(cuX + n <= screenLines[cuY].count()); - screenLines[cuY].remove(cuX,n); + screenLines[cuY].remove(cuX, n); } -void Screen::insertChars(int n) -{ - if (n == 0) n = 1; // Default +void Screen::insertChars(int n) { + if (n == 0) + n = 1; // Default - if ( screenLines[cuY].size() < cuX ) + if (screenLines[cuY].size() < cuX) screenLines[cuY].resize(cuX); - screenLines[cuY].insert(cuX,n,' '); + screenLines[cuY].insert(cuX, n, ' '); - if ( screenLines[cuY].count() > columns ) + if (screenLines[cuY].count() > columns) screenLines[cuY].resize(columns); } -void Screen::repeatChars(int count) - //=REP -{ - if (count == 0) - { +void Screen::repeatChars(int count) { + if (count == 0) { count = 1; } /** @@ -256,99 +221,88 @@ void Screen::repeatChars(int count) * character (those other than escape sequences). So, lastDrawnChar can be * safely used. */ - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { displayCharacter(lastDrawnChar); } } -void Screen::deleteLines(int n) -{ - if (n == 0) n = 1; // Default - scrollUp(cuY,n); +void Screen::deleteLines(int n) { + if (n == 0) + n = 1; // Default + scrollUp(cuY, n); } -void Screen::insertLines(int n) -{ - if (n == 0) n = 1; // Default - scrollDown(cuY,n); +void Screen::insertLines(int n) { + if (n == 0) + n = 1; // Default + scrollDown(cuY, n); } -void Screen::setMode(int m) -{ +void Screen::setMode(int m) { currentModes[m] = true; - switch(m) - { - case MODE_Origin : cuX = 0; cuY = _topMargin; break; //FIXME: home + switch (m) { + case MODE_Origin: + cuX = 0; + cuY = _topMargin; + break; // FIXME: home } } -void Screen::resetMode(int m) -{ +void Screen::resetMode(int m) { currentModes[m] = false; - switch(m) - { - case MODE_Origin : cuX = 0; cuY = 0; break; //FIXME: home + switch (m) { + case MODE_Origin: + cuX = 0; + cuY = 0; + break; // FIXME: home } } -void Screen::saveMode(int m) -{ - savedModes[m] = currentModes[m]; -} +void Screen::saveMode(int m) { savedModes[m] = currentModes[m]; } -void Screen::restoreMode(int m) -{ - currentModes[m] = savedModes[m]; -} +void Screen::restoreMode(int m) { currentModes[m] = savedModes[m]; } -bool Screen::getMode(int m) const -{ - return currentModes[m]; -} +bool Screen::getMode(int m) const { return currentModes[m]; } -void Screen::saveCursor() -{ +void Screen::saveCursor() { savedState.cursorColumn = cuX; - savedState.cursorLine = cuY; + savedState.cursorLine = cuY; savedState.rendition = currentRendition; savedState.foreground = currentForeground; savedState.background = currentBackground; } -void Screen::restoreCursor() -{ - cuX = qMin(savedState.cursorColumn,columns-1); - cuY = qMin(savedState.cursorLine,lines-1); - currentRendition = savedState.rendition; - currentForeground = savedState.foreground; - currentBackground = savedState.background; +void Screen::restoreCursor() { + cuX = qMin(savedState.cursorColumn, columns - 1); + cuY = qMin(savedState.cursorLine, lines - 1); + currentRendition = savedState.rendition; + currentForeground = savedState.foreground; + currentBackground = savedState.background; updateEffectiveRendition(); } -void Screen::resizeImage(int new_lines, int new_columns) -{ - if ((new_lines==lines) && (new_columns==columns)) return; +void Screen::resizeImage(int new_lines, int new_columns) { + if ((new_lines == lines) && (new_columns == columns)) + return; - if (cuY > new_lines-1) - { // attempt to preserve focus and lines - _bottomMargin = lines-1; //FIXME: margin lost - for (int i = 0; i < cuY-(new_lines-1); i++) - { - addHistLine(); scrollUp(0,1); + if (cuY > new_lines - 1) { // attempt to preserve focus and lines + _bottomMargin = lines - 1; // FIXME: margin lost + for (int i = 0; i < cuY - (new_lines - 1); i++) { + addHistLine(); + scrollUp(0, 1); } } // create new screen lines and copy from old to new - ImageLine* newScreenLines = new ImageLine[new_lines+1]; - for (int i=0; i < qMin(lines,new_lines+1) ;i++) - newScreenLines[i]=screenLines[i]; - for (int i=lines;(i > 0) && (i 0) && (i < new_lines + 1); i++) + newScreenLines[i].resize(new_columns); - lineProperties.resize(new_lines+1); - for (int i=lines;(i > 0) && (i 0) && (i < new_lines + 1); i++) lineProperties[i] = LINE_DEFAULT; clearSelection(); @@ -358,76 +312,68 @@ void Screen::resizeImage(int new_lines, int new_columns) lines = new_lines; columns = new_columns; - cuX = qMin(cuX,columns-1); - cuY = qMin(cuY,lines-1); + cuX = qMin(cuX, columns - 1); + cuY = qMin(cuY, lines - 1); // FIXME: try to keep values, evtl. - _topMargin=0; - _bottomMargin=lines-1; + _topMargin = 0; + _bottomMargin = lines - 1; initTabStops(); clearSelection(); } -void Screen::setDefaultMargins() -{ +void Screen::setDefaultMargins() { _topMargin = 0; - _bottomMargin = lines-1; + _bottomMargin = lines - 1; } - /* - Clarifying rendition here and in the display. - - currently, the display's color table is - 0 1 2 .. 9 10 .. 17 - dft_fg, dft_bg, dim 0..7, intensive 0..7 - - currentForeground, currentBackground contain values 0..8; - - 0 = default color - - 1..8 = ansi specified color - - re_fg, re_bg contain values 0..17 - due to the TerminalDisplay's color table - - rendition attributes are - - attr widget screen - -------------- ------ ------ - RE_UNDERLINE XX XX affects foreground only - RE_BLINK XX XX affects foreground only - RE_BOLD XX XX affects foreground only - RE_REVERSE -- XX - RE_TRANSPARENT XX -- affects background only - RE_INTENSIVE XX -- affects foreground only - - Note that RE_BOLD is used in both widget - and screen rendition. Since xterm/vt102 - is to poor to distinguish between bold - (which is a font attribute) and intensive - (which is a color attribute), we translate - this and RE_BOLD in falls eventually apart - into RE_BOLD and RE_INTENSIVE. - */ - -void Screen::reverseRendition(Character& p) const -{ + Clarifying rendition here and in the display. + + currently, the display's color table is + 0 1 2 .. 9 10 .. 17 + dft_fg, dft_bg, dim 0..7, intensive 0..7 + + currentForeground, currentBackground contain values 0..8; + - 0 = default color + - 1..8 = ansi specified color + + re_fg, re_bg contain values 0..17 + due to the TerminalDisplay's color table + + rendition attributes are + + attr widget screen + -------------- ------ ------ + RE_UNDERLINE XX XX affects foreground only + RE_BLINK XX XX affects foreground only + RE_BOLD XX XX affects foreground only + RE_REVERSE -- XX + RE_TRANSPARENT XX -- affects background only + RE_INTENSIVE XX -- affects foreground only + + Note that RE_BOLD is used in both widget + and screen rendition. Since xterm/vt102 + is to poor to distinguish between bold + (which is a font attribute) and intensive + (which is a color attribute), we translate + this and RE_BOLD in falls eventually apart + into RE_BOLD and RE_INTENSIVE. +*/ +void Screen::reverseRendition(Character &p) const { CharacterColor f = p.foregroundColor; CharacterColor b = p.backgroundColor; p.foregroundColor = b; - p.backgroundColor = f; //p->r &= ~RE_TRANSPARENT; + p.backgroundColor = f; // p->r &= ~RE_TRANSPARENT; } -void Screen::updateEffectiveRendition() -{ +void Screen::updateEffectiveRendition() { effectiveRendition = currentRendition; - if (currentRendition & RE_REVERSE) - { + if (currentRendition & RE_REVERSE) { effectiveForeground = currentBackground; effectiveBackground = currentForeground; - } - else - { + } else { effectiveForeground = currentForeground; effectiveBackground = currentBackground; } @@ -436,27 +382,23 @@ void Screen::updateEffectiveRendition() effectiveForeground.setIntensive(); } -void Screen::copyFromHistory(Character* dest, int startLine, int count) const -{ - Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= history->getLines() ); +void Screen::copyFromHistory(Character *dest, int startLine, int count) const { + Q_ASSERT(startLine >= 0 && count > 0 && + startLine + count <= history->getLines()); - for (int line = startLine; line < startLine + count; line++) - { - const int length = qMin(columns,history->getLineLen(line)); - const int destLineOffset = (line-startLine)*columns; + for (int line = startLine; line < startLine + count; line++) { + const int length = qMin(columns, history->getLineLen(line)); + const int destLineOffset = (line - startLine) * columns; - history->getCells(line,0,length,dest + destLineOffset); + history->getCells(line, 0, length, dest + destLineOffset); for (int column = length; column < columns; column++) - dest[destLineOffset+column] = defaultChar; + dest[destLineOffset + column] = defaultChar; // invert selected text - if (selBegin !=-1) - { - for (int column = 0; column < columns; column++) - { - if (isSelected(column,line)) - { + if (selBegin != -1) { + for (int column = 0; column < columns; column++) { + if (isSelected(column, line)) { reverseRendition(dest[destLineOffset + column]); } } @@ -464,83 +406,80 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const } } -void Screen::copyFromScreen(Character* dest , int startLine , int count) const -{ - Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); +void Screen::copyFromScreen(Character *dest, int startLine, int count) const { + Q_ASSERT(startLine >= 0 && count > 0 && startLine + count <= lines); - for (int line = startLine; line < (startLine+count) ; line++) - { - int srcLineStartIndex = line*columns; - int destLineStartIndex = (line-startLine)*columns; + for (int line = startLine; line < (startLine + count); line++) { + int srcLineStartIndex = line * columns; + int destLineStartIndex = (line - startLine) * columns; - for (int column = 0; column < columns; column++) - { + for (int column = 0; column < columns; column++) { int srcIndex = srcLineStartIndex + column; int destIndex = destLineStartIndex + column; - dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); + dest[destIndex] = screenLines[srcIndex / columns].value( + srcIndex % columns, defaultChar); // invert selected text - if (selBegin != -1 && isSelected(column,line + history->getLines())) + if (selBegin != -1 && isSelected(column, line + history->getLines())) reverseRendition(dest[destIndex]); } } } -void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const -{ - Q_ASSERT( startLine >= 0 ); - Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); +void Screen::getImage(Character *dest, int size, int startLine, + int endLine) const { + Q_ASSERT(startLine >= 0); + Q_ASSERT(endLine >= startLine && endLine < history->getLines() + lines); const int mergedLines = endLine - startLine + 1; - Q_ASSERT( size >= mergedLines * columns ); - Q_UNUSED( size ); + Q_ASSERT(size >= mergedLines * columns); + Q_UNUSED(size); - const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); + const int linesInHistoryBuffer = + qBound(0, history->getLines() - startLine, mergedLines); const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; // copy lines from history buffer if (linesInHistoryBuffer > 0) - copyFromHistory(dest,startLine,linesInHistoryBuffer); + copyFromHistory(dest, startLine, linesInHistoryBuffer); // copy lines from screen buffer if (linesInScreenBuffer > 0) - copyFromScreen(dest + linesInHistoryBuffer*columns, - startLine + linesInHistoryBuffer - history->getLines(), - linesInScreenBuffer); + copyFromScreen(dest + linesInHistoryBuffer * columns, + startLine + linesInHistoryBuffer - history->getLines(), + linesInScreenBuffer); // invert display when in screen mode - if (getMode(MODE_Screen)) - { - for (int i = 0; i < mergedLines*columns; i++) + if (getMode(MODE_Screen)) { + for (int i = 0; i < mergedLines * columns; i++) reverseRendition(dest[i]); // for reverse display } // mark the character at the current cursor position int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer); - if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) + if (getMode(MODE_Cursor) && cursorIndex < columns * mergedLines) dest[cursorIndex].rendition |= RE_CURSOR; } -QVector Screen::getLineProperties( int startLine , int endLine ) const -{ - Q_ASSERT( startLine >= 0 ); - Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); +QVector Screen::getLineProperties(int startLine, + int endLine) const { + Q_ASSERT(startLine >= 0); + Q_ASSERT(endLine >= startLine && endLine < history->getLines() + lines); - const int mergedLines = endLine-startLine+1; - const int linesInHistory = qBound(0,history->getLines()-startLine,mergedLines); + const int mergedLines = endLine - startLine + 1; + const int linesInHistory = + qBound(0, history->getLines() - startLine, mergedLines); const int linesInScreen = mergedLines - linesInHistory; QVector result(mergedLines); int index = 0; // copy properties for lines in history - for (int line = startLine; line < startLine + linesInHistory; line++) - { - //TODO Support for line properties other than wrapped lines - if (history->isWrappedLine(line)) - { + for (int line = startLine; line < startLine + linesInHistory; line++) { + // TODO Support for line properties other than wrapped lines + if (history->isWrappedLine(line)) { result[index] = (LineProperty)(result[index] | LINE_WRAPPED); } index++; @@ -548,54 +487,55 @@ QVector Screen::getLineProperties( int startLine , int endLine ) c // copy properties for lines in screen buffer const int firstScreenLine = startLine + linesInHistory - history->getLines(); - for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++) - { - result[index]=lineProperties[line]; + for (int line = firstScreenLine; line < firstScreenLine + linesInScreen; + line++) { + result[index] = lineProperties[line]; index++; } return result; } -void Screen::reset(bool clearScreen) -{ - setMode(MODE_Wrap ); saveMode(MODE_Wrap ); // wrap at end of margin - resetMode(MODE_Origin); saveMode(MODE_Origin); // position refers to [1,1] - resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke - setMode(MODE_Cursor); // cursor visible - resetMode(MODE_Screen); // screen not inverse +void Screen::reset(bool clearScreen) { + setMode(MODE_Wrap); + saveMode(MODE_Wrap); // wrap at end of margin + resetMode(MODE_Origin); + saveMode(MODE_Origin); // position refers to [1,1] + resetMode(MODE_Insert); + saveMode(MODE_Insert); // overstroke + setMode(MODE_Cursor); // cursor visible + resetMode(MODE_Screen); // screen not inverse resetMode(MODE_NewLine); - _topMargin=0; - _bottomMargin=lines-1; + _topMargin = 0; + _bottomMargin = lines - 1; setDefaultRendition(); saveCursor(); - if ( clearScreen ) + if (clearScreen) clear(); } -void Screen::clear() -{ +void Screen::clear() { clearEntireScreen(); home(); } -void Screen::backspace() -{ - cuX = qMin(columns-1,cuX); // nowrap! - cuX = qMax(0,cuX-1); +void Screen::backspace() { + cuX = qMin(columns - 1, cuX); // nowrap! + cuX = qMax(0, cuX - 1); - if (screenLines[cuY].size() < cuX+1) - screenLines[cuY].resize(cuX+1); -#if 0 //TODO: implement when unicode_width is fixed, we need more backspace/cursorMove + if (screenLines[cuY].size() < cuX + 1) + screenLines[cuY].resize(cuX + 1); +#if 0 // TODO: implement when unicode_width is fixed, we need more + // backspace/cursorMove wchar_t c = 0; if(cuX <= 0) { if(cuY > 0) { uint32_t endx = screenLines[cuY-1].size(); if(endx > 0) { - c = screenLines[cuY-1][endx-1].character; + c = screenLines[cuY-1][endx-1].character; } } } else { @@ -609,77 +549,73 @@ void Screen::backspace() cuX = qMax(0,cuX-1); if (screenLines[cuY].size() < cuX+1) - screenLines[cuY].resize(cuX+1); + screenLines[cuY].resize(cuX+1); } } #endif } -void Screen::tab(int n) -{ +void Screen::tab(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) n = 1; - while((n > 0) && (cuX < columns-1)) - { + if (n == 0) + n = 1; + while ((n > 0) && (cuX < columns - 1)) { cursorRight(1); - while((cuX < columns-1) && !tabStops[cuX]) + while ((cuX < columns - 1) && !tabStops[cuX]) cursorRight(1); n--; } } -void Screen::backtab(int n) -{ +void Screen::backtab(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) n = 1; - while((n > 0) && (cuX > 0)) - { - cursorLeft(1); while((cuX > 0) && !tabStops[cuX]) cursorLeft(1); + if (n == 0) + n = 1; + while ((n > 0) && (cuX > 0)) { + cursorLeft(1); + while ((cuX > 0) && !tabStops[cuX]) + cursorLeft(1); n--; } } -void Screen::clearTabStops() -{ - for (int i = 0; i < columns; i++) tabStops[i] = false; +void Screen::clearTabStops() { + for (int i = 0; i < columns; i++) + tabStops[i] = false; } -void Screen::changeTabStop(bool set) -{ - if (cuX >= columns) return; +void Screen::changeTabStop(bool set) { + if (cuX >= columns) + return; tabStops[cuX] = set; } -void Screen::initTabStops() -{ +void Screen::initTabStops() { tabStops.resize(columns); // Arrg! The 1st tabstop has to be one longer than the other. // i.e. the kids start counting from 0 instead of 1. // Other programs might behave correctly. Be aware. for (int i = 0; i < columns; i++) - tabStops[i] = (i%8 == 0 && i != 0); + tabStops[i] = (i % 8 == 0 && i != 0); } -void Screen::newLine() -{ +void Screen::newLine() { if (getMode(MODE_NewLine)) toStartOfLine(); index(); } -void Screen::checkSelection(int from, int to) -{ +void Screen::checkSelection(int from, int to) { if (selBegin == -1) return; int scr_TL = loc(0, history->getLines()); - //Clear entire selection if it overlaps region [from, to] - if ( (selBottomRight >= (from+scr_TL)) && (selTopLeft <= (to+scr_TL)) ) + // Clear entire selection if it overlaps region [from, to] + if ((selBottomRight >= (from + scr_TL)) && (selTopLeft <= (to + scr_TL))) clearSelection(); } -void Screen::displayCharacter(wchar_t c) -{ +void Screen::displayCharacter(wchar_t c) { // Note that VT100 does wrapping BEFORE putting the character. // This has impact on the assumption of valid cursor positions. // We indicate the fact that a newline has to be triggered by @@ -689,30 +625,29 @@ void Screen::displayCharacter(wchar_t c) if (w <= 0) return; - if (cuX+w > columns) { + if (cuX + w > columns) { if (getMode(MODE_Wrap)) { lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED); nextLine(); - } - else - cuX = columns-w; + } else + cuX = columns - w; } // ensure current line vector has enough elements int size = screenLines[cuY].size(); - if (size < cuX+w) - { - screenLines[cuY].resize(cuX+w); + if (size < cuX + w) { + screenLines[cuY].resize(cuX + w); } - if (getMode(MODE_Insert)) insertChars(w); + if (getMode(MODE_Insert)) + insertChars(w); - lastPos = loc(cuX,cuY); + lastPos = loc(cuX, cuY); // check if selection is still valid. checkSelection(lastPos, lastPos); - Character& currentChar = screenLines[cuY][cuX]; + Character ¤tChar = screenLines[cuY][cuX]; currentChar.character = c; currentChar.foregroundColor = effectiveForeground; @@ -723,14 +658,13 @@ void Screen::displayCharacter(wchar_t c) int i = 0; int newCursorX = cuX + w--; - while(w) - { + while (w) { i++; - if ( screenLines[cuY].size() < cuX + i + 1 ) - screenLines[cuY].resize(cuX+i+1); + if (screenLines[cuY].size() < cuX + i + 1) + screenLines[cuY].resize(cuX + i + 1); - Character& ch = screenLines[cuY][cuX + i]; + Character &ch = screenLines[cuY][cuX + i]; ch.character = 0; ch.foregroundColor = effectiveForeground; ch.backgroundColor = effectiveBackground; @@ -741,50 +675,34 @@ void Screen::displayCharacter(wchar_t c) cuX = newCursorX; } -void Screen::compose(const QString& /*compose*/) -{ - Q_ASSERT( 0 /*Not implemented yet*/ ); +void Screen::compose(const QString & /*compose*/) { + Q_ASSERT(0 /*Not implemented yet*/); /* if (lastPos == -1) - return; + return; - QChar c(image[lastPos].character); - compose.prepend(c); + QChar c(image[lastPos].character); + compose.prepend(c); //compose.compose(); ### FIXME! image[lastPos].character = compose[0].unicode();*/ } -int Screen::scrolledLines() const -{ - return _scrolledLines; -} -int Screen::droppedLines() const -{ - return _droppedLines; -} -void Screen::resetDroppedLines() -{ - _droppedLines = 0; -} -void Screen::resetScrolledLines() -{ - _scrolledLines = 0; -} +int Screen::scrolledLines() const { return _scrolledLines; } +int Screen::droppedLines() const { return _droppedLines; } +void Screen::resetDroppedLines() { _droppedLines = 0; } +void Screen::resetScrolledLines() { _scrolledLines = 0; } -void Screen::scrollUp(int n) -{ - if (n == 0) n = 1; // Default - if (_topMargin == 0) addHistLine(); // history.history +void Screen::scrollUp(int n) { + if (n == 0) + n = 1; // Default + if (_topMargin == 0) + addHistLine(); // history.history scrollUp(_topMargin, n); } -QRect Screen::lastScrolledRegion() const -{ - return _lastScrolledRegion; -} +QRect Screen::lastScrolledRegion() const { return _lastScrolledRegion; } -void Screen::scrollUp(int from, int n) -{ +void Screen::scrollUp(int from, int n) { if (n <= 0) return; if (from > _bottomMargin) @@ -793,73 +711,65 @@ void Screen::scrollUp(int from, int n) n = _bottomMargin + 1 - from; _scrolledLines -= n; - _lastScrolledRegion = QRect(0,_topMargin,columns-1,(_bottomMargin-_topMargin)); + _lastScrolledRegion = + QRect(0, _topMargin, columns - 1, (_bottomMargin - _topMargin)); - //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. - moveImage(loc(0,from),loc(0,from+n),loc(columns,_bottomMargin)); - clearImage(loc(0,_bottomMargin-n+1),loc(columns-1,_bottomMargin),' '); + // FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + moveImage(loc(0, from), loc(0, from + n), loc(columns, _bottomMargin)); + clearImage(loc(0, _bottomMargin - n + 1), loc(columns - 1, _bottomMargin), + ' '); } -void Screen::scrollDown(int n) -{ - if (n == 0) n = 1; // Default +void Screen::scrollDown(int n) { + if (n == 0) + n = 1; // Default scrollDown(_topMargin, n); } -void Screen::scrollDown(int from, int n) -{ +void Screen::scrollDown(int from, int n) { _scrolledLines += n; - //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + // FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. if (n <= 0) return; if (from > _bottomMargin) return; if (from + n > _bottomMargin) n = _bottomMargin - from; - moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n)); - clearImage(loc(0,from),loc(columns-1,from+n-1),' '); + moveImage(loc(0, from + n), loc(0, from), + loc(columns - 1, _bottomMargin - n)); + clearImage(loc(0, from), loc(columns - 1, from + n - 1), ' '); } -void Screen::setCursorYX(int y, int x) -{ - setCursorY(y); setCursorX(x); +void Screen::setCursorYX(int y, int x) { + setCursorY(y); + setCursorX(x); } -void Screen::setCursorX(int x) -{ - if (x == 0) x = 1; // Default - x -= 1; // Adjust - cuX = qMax(0,qMin(columns-1, x)); +void Screen::setCursorX(int x) { + if (x == 0) + x = 1; // Default + x -= 1; // Adjust + cuX = qMax(0, qMin(columns - 1, x)); } -void Screen::setCursorY(int y) -{ - if (y == 0) y = 1; // Default - y -= 1; // Adjust - cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? _topMargin : 0) )); +void Screen::setCursorY(int y) { + if (y == 0) + y = 1; // Default + y -= 1; // Adjust + cuY = qMax(0, qMin(lines - 1, y + (getMode(MODE_Origin) ? _topMargin : 0))); } -void Screen::home() -{ +void Screen::home() { cuX = 0; cuY = 0; } -void Screen::toStartOfLine() -{ - cuX = 0; -} +void Screen::toStartOfLine() { cuX = 0; } -int Screen::getCursorX() const -{ - return cuX; -} +int Screen::getCursorX() const { return cuX; } -int Screen::getCursorY() const -{ - return cuY; -} +int Screen::getCursorY() const { return cuY; } QString Screen::getScreenText(int row1, int col1, int row2, int col2, int mode) { Q_ASSERT(row1 >= 0 && row1 < lines); @@ -875,24 +785,28 @@ QString Screen::getScreenText(int row1, int col1, int row2, int col2, int mode) if (mode == 1) { for (int i = startLine; i <= endLine; i++) { - if(screenLines->size() <= i) break; + if (screenLines->size() <= i) + break; for (int j = startCol; j <= endCol; j++) { - if(screenLines[i].count() <= j) break; + if (screenLines[i].count() <= j) + break; wchar_t c = screenLines[i][j].character; text += QChar(c); } } } else if (mode == 2) { for (int i = startLine; i <= endLine; i++) { - if(screenLines->size() <= i) break; + if (screenLines->size() <= i) + break; int size = 0; for (int j = startCol; j <= endCol; j++) { - if(screenLines[i].count() <= j) break; + if (screenLines[i].count() <= j) + break; wchar_t c = screenLines[i][j].character; text += QChar(c); size++; } - if(size != 0) { + if (size != 0) { text += '\n'; } } @@ -901,97 +815,87 @@ QString Screen::getScreenText(int row1, int col1, int row2, int col2, int mode) return text; } -void Screen::clearImage(int loca, int loce, char c) -{ - int scr_TL=loc(0,history->getLines()); - //FIXME: check positions +void Screen::clearImage(int loca, int loce, char c) { + int scr_TL = loc(0, history->getLines()); + // FIXME: check positions - //Clear entire selection if it overlaps region to be moved... - if ( (selBottomRight > (loca+scr_TL) )&&(selTopLeft < (loce+scr_TL)) ) - { + // Clear entire selection if it overlaps region to be moved... + if ((selBottomRight > (loca + scr_TL)) && (selTopLeft < (loce + scr_TL))) { clearSelection(); } - int topLine = loca/columns; - int bottomLine = loce/columns; + int topLine = loca / columns; + int bottomLine = loce / columns; - Character clearCh(c,currentForeground,currentBackground,DEFAULT_RENDITION); + Character clearCh(c, currentForeground, currentBackground, DEFAULT_RENDITION); - //if the character being used to clear the area is the same as the - //default character, the affected lines can simply be shrunk. + // if the character being used to clear the area is the same as the + // default character, the affected lines can simply be shrunk. bool isDefaultCh = (clearCh == Character()); - for (int y=topLine;y<=bottomLine;y++) - { + for (int y = topLine; y <= bottomLine; y++) { lineProperties[y] = 0; - int endCol = ( y == bottomLine) ? loce%columns : columns-1; - int startCol = ( y == topLine ) ? loca%columns : 0; + int endCol = (y == bottomLine) ? loce % columns : columns - 1; + int startCol = (y == topLine) ? loca % columns : 0; - QVector& line = screenLines[y]; + QVector &line = screenLines[y]; - if ( isDefaultCh && endCol == columns-1 ) - { + if (isDefaultCh && endCol == columns - 1) { line.resize(startCol); - } - else - { + } else { if (line.size() < endCol + 1) - line.resize(endCol+1); + line.resize(endCol + 1); - Character* data = line.data(); - for (int i=startCol;i<=endCol;i++) - data[i]=clearCh; + Character *data = line.data(); + for (int i = startCol; i <= endCol; i++) + data[i] = clearCh; } } } -void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) -{ - Q_ASSERT( sourceBegin <= sourceEnd ); +void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) { + Q_ASSERT(sourceBegin <= sourceEnd); - int lines=(sourceEnd-sourceBegin)/columns; + int lines = (sourceEnd - sourceBegin) / columns; - //move screen image and line properties: - //the source and destination areas of the image may overlap, - //so it matters that we do the copy in the right order - - //forwards if dest < sourceBegin or backwards otherwise. + // move screen image and line properties: + // the source and destination areas of the image may overlap, + // so it matters that we do the copy in the right order - + // forwards if dest < sourceBegin or backwards otherwise. //(search the web for 'memmove implementation' for details) - if (dest < sourceBegin) - { - for (int i=0;i<=lines;i++) - { - screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; - lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; + if (dest < sourceBegin) { + for (int i = 0; i <= lines; i++) { + screenLines[(dest / columns) + i] = + screenLines[(sourceBegin / columns) + i]; + lineProperties[(dest / columns) + i] = + lineProperties[(sourceBegin / columns) + i]; } - } - else - { - for (int i=lines;i>=0;i--) - { - screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; - lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; + } else { + for (int i = lines; i >= 0; i--) { + screenLines[(dest / columns) + i] = + screenLines[(sourceBegin / columns) + i]; + lineProperties[(dest / columns) + i] = + lineProperties[(sourceBegin / columns) + i]; } } - if (lastPos != -1) - { + if (lastPos != -1) { int diff = dest - sourceBegin; // Scroll by this amount lastPos += diff; - if ((lastPos < 0) || (lastPos >= (lines*columns))) + if ((lastPos < 0) || (lastPos >= (lines * columns))) lastPos = -1; } // Adjust selection to follow scroll. - if (selBegin != -1) - { + if (selBegin != -1) { bool beginIsTL = (selBegin == selTopLeft); int diff = dest - sourceBegin; // Scroll by this amount - int scr_TL=loc(0,history->getLines()); - int srca = sourceBegin+scr_TL; // Translate index from screen to global - int srce = sourceEnd+scr_TL; // Translate index from screen to global - int desta = srca+diff; - int deste = srce+diff; + int scr_TL = loc(0, history->getLines()); + int srca = sourceBegin + scr_TL; // Translate index from screen to global + int srce = sourceEnd + scr_TL; // Translate index from screen to global + int desta = srca + diff; + int deste = srce + diff; if ((selTopLeft >= srca) && (selTopLeft <= srce)) selTopLeft += diff; @@ -1003,12 +907,9 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) else if ((selBottomRight >= desta) && (selBottomRight <= deste)) selBottomRight = -1; // Clear selection (see below) - if (selBottomRight < 0) - { + if (selBottomRight < 0) { clearSelection(); - } - else - { + } else { if (selTopLeft < 0) selTopLeft = 0; } @@ -1020,156 +921,128 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) } } -void Screen::clearToEndOfScreen() -{ - clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' '); +void Screen::clearToEndOfScreen() { + clearImage(loc(cuX, cuY), loc(columns - 1, lines - 1), ' '); } -void Screen::clearToBeginOfScreen() -{ - clearImage(loc(0,0),loc(cuX,cuY),' '); +void Screen::clearToBeginOfScreen() { + clearImage(loc(0, 0), loc(cuX, cuY), ' '); } -void Screen::clearEntireScreen() -{ +void Screen::clearEntireScreen() { // Add entire screen to history - for (int i = 0; i < (lines-1); i++) - { - addHistLine(); scrollUp(0,1); + for (int i = 0; i < (lines - 1); i++) { + addHistLine(); + scrollUp(0, 1); } - clearImage(loc(0,0),loc(columns-1,lines-1),' '); + clearImage(loc(0, 0), loc(columns - 1, lines - 1), ' '); } /*! fill screen with 'E' - This is to aid screen alignment - */ + This is to aid screen alignment + */ -void Screen::helpAlign() -{ - clearImage(loc(0,0),loc(columns-1,lines-1),'E'); +void Screen::helpAlign() { + clearImage(loc(0, 0), loc(columns - 1, lines - 1), 'E'); } -void Screen::clearToEndOfLine() -{ - clearImage(loc(cuX,cuY),loc(columns-1,cuY),' '); +void Screen::clearToEndOfLine() { + clearImage(loc(cuX, cuY), loc(columns - 1, cuY), ' '); } -void Screen::clearToBeginOfLine() -{ - clearImage(loc(0,cuY),loc(cuX,cuY),' '); +void Screen::clearToBeginOfLine() { + clearImage(loc(0, cuY), loc(cuX, cuY), ' '); } -void Screen::clearEntireLine() -{ - clearImage(loc(0,cuY),loc(columns-1,cuY),' '); +void Screen::clearEntireLine() { + clearImage(loc(0, cuY), loc(columns - 1, cuY), ' '); } -void Screen::setRendition(int re) -{ +void Screen::setRendition(int re) { currentRendition |= re; updateEffectiveRendition(); } -void Screen::resetRendition(int re) -{ +void Screen::resetRendition(int re) { currentRendition &= ~re; updateEffectiveRendition(); } -void Screen::setDefaultRendition() -{ - setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); - setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); - currentRendition = DEFAULT_RENDITION; +void Screen::setDefaultRendition() { + setForeColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); + setBackColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); + currentRendition = DEFAULT_RENDITION; updateEffectiveRendition(); } -void Screen::setForeColor(int space, int color) -{ +void Screen::setForeColor(int space, int color) { currentForeground = CharacterColor(space, color); - if ( currentForeground.isValid() ) + if (currentForeground.isValid()) updateEffectiveRendition(); else - setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); + setForeColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); } -void Screen::setBackColor(int space, int color) -{ +void Screen::setBackColor(int space, int color) { currentBackground = CharacterColor(space, color); - if ( currentBackground.isValid() ) + if (currentBackground.isValid()) updateEffectiveRendition(); else - setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); + setBackColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); } -void Screen::clearSelection() -{ +void Screen::clearSelection() { selBottomRight = -1; selTopLeft = -1; selBegin = -1; } -bool Screen::isClearSelection() -{ - return selBottomRight == -1 && - selTopLeft == -1 && - selBegin == -1; +bool Screen::isClearSelection() { + return selBottomRight == -1 && selTopLeft == -1 && selBegin == -1; } -void Screen::getSelectionStart(int& column , int& line) const -{ - if ( selTopLeft != -1 ) - { +void Screen::getSelectionStart(int &column, int &line) const { + if (selTopLeft != -1) { column = selTopLeft % columns; line = selTopLeft / columns; - } - else - { + } else { column = cuX + getHistLines(); line = cuY + getHistLines(); } } -void Screen::getSelectionEnd(int& column , int& line) const -{ - if ( selBottomRight != -1 ) - { +void Screen::getSelectionEnd(int &column, int &line) const { + if (selBottomRight != -1) { column = selBottomRight % columns; line = selBottomRight / columns; - } - else - { + } else { column = cuX + getHistLines(); line = cuY + getHistLines(); } } -void Screen::setSelectionStart(const int x, const int y, const bool mode) -{ - selBegin = loc(x,y); +void Screen::setSelectionStart(const int x, const int y, const bool mode) { + selBegin = loc(x, y); /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) selBegin--; + if (x == columns) + selBegin--; selBottomRight = selBegin; selTopLeft = selBegin; blockSelectionMode = mode; } -void Screen::setSelectionEnd( const int x, const int y) -{ +void Screen::setSelectionEnd(const int x, const int y) { if (selBegin == -1) return; - int endPos = loc(x,y); + int endPos = loc(x, y); - if (endPos < selBegin) - { + if (endPos < selBegin) { selTopLeft = endPos; selBottomRight = selBegin; - } - else - { + } else { /* FIXME, HACK to correct for x too far to the right... */ if (x == columns) endPos--; @@ -1179,205 +1052,179 @@ void Screen::setSelectionEnd( const int x, const int y) } // Normalize the selection in column mode - if (blockSelectionMode) - { + if (blockSelectionMode) { int topRow = selTopLeft / columns; int topColumn = selTopLeft % columns; int bottomRow = selBottomRight / columns; int bottomColumn = selBottomRight % columns; - selTopLeft = loc(qMin(topColumn,bottomColumn),topRow); - selBottomRight = loc(qMax(topColumn,bottomColumn),bottomRow); + selTopLeft = loc(qMin(topColumn, bottomColumn), topRow); + selBottomRight = loc(qMax(topColumn, bottomColumn), bottomRow); } } -bool Screen::isSelected( const int x,const int y) const -{ +bool Screen::isSelected(const int x, const int y) const { bool columnInSelection = true; - if (blockSelectionMode) - { - columnInSelection = x >= (selTopLeft % columns) && - x <= (selBottomRight % columns); + if (blockSelectionMode) { + columnInSelection = + x >= (selTopLeft % columns) && x <= (selBottomRight % columns); } - int pos = loc(x,y); + int pos = loc(x, y); return pos >= selTopLeft && pos <= selBottomRight && columnInSelection; } -QString Screen::selectedText(bool preserveLineBreaks) const -{ +QString Screen::selectedText(bool preserveLineBreaks) const { QString result; QTextStream stream(&result, QIODevice::ReadWrite); PlainTextDecoder decoder; decoder.begin(&stream); - writeSelectionToStream(&decoder , preserveLineBreaks); + writeSelectionToStream(&decoder, preserveLineBreaks); decoder.end(); return result; } -bool Screen::isSelectionValid() const -{ +bool Screen::isSelectionValid() const { return selTopLeft >= 0 && selBottomRight >= 0; } -void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , - bool preserveLineBreaks) const -{ +void Screen::writeSelectionToStream(TerminalCharacterDecoder *decoder, + bool preserveLineBreaks) const { if (!isSelectionValid()) return; - writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); + writeToStream(decoder, selTopLeft, selBottomRight, preserveLineBreaks); } -void Screen::writeToStream(TerminalCharacterDecoder* decoder, - int startIndex, int endIndex, - bool preserveLineBreaks) const -{ +void Screen::writeToStream(TerminalCharacterDecoder *decoder, int startIndex, + int endIndex, bool preserveLineBreaks) const { int top = startIndex / columns; int left = startIndex % columns; int bottom = endIndex / columns; int right = endIndex % columns; - Q_ASSERT( top >= 0 && left >= 0 && bottom >= 0 && right >= 0 ); + Q_ASSERT(top >= 0 && left >= 0 && bottom >= 0 && right >= 0); - for (int y=top;y<=bottom;y++) - { + for (int y = top; y <= bottom; y++) { int start = 0; - if ( y == top || blockSelectionMode ) start = left; + if (y == top || blockSelectionMode) + start = left; int count = -1; - if ( y == bottom || blockSelectionMode ) count = right - start + 1; + if (y == bottom || blockSelectionMode) + count = right - start + 1; - const bool appendNewLine = ( y != bottom ); - int copied = copyLineToStream( y, - start, - count, - decoder, - appendNewLine, - preserveLineBreaks ); + const bool appendNewLine = (y != bottom); + int copied = copyLineToStream(y, start, count, decoder, appendNewLine, + preserveLineBreaks); // if the selection goes beyond the end of the last line then // append a new line character. // // this makes it possible to 'select' a trailing new line character after // the text on a line. - if ( y == bottom && - copied < count ) - { + if (y == bottom && copied < count) { Character newLineChar('\n'); - decoder->decodeLine(&newLineChar,1,0); + decoder->decodeLine(&newLineChar, 1, 0); } } } -int Screen::copyLineToStream(int line , - int start, - int count, - TerminalCharacterDecoder* decoder, - bool appendNewLine, - bool preserveLineBreaks) const -{ - //buffer to hold characters for decoding - //the buffer is static to avoid initialising every - //element on each call to copyLineToStream +int Screen::copyLineToStream(int line, int start, int count, + TerminalCharacterDecoder *decoder, + bool appendNewLine, + bool preserveLineBreaks) const { + // buffer to hold characters for decoding + // the buffer is static to avoid initialising every + // element on each call to copyLineToStream //(which is unnecessary since all elements will be overwritten anyway) static const int MAX_CHARS = 1024; static Character characterBuffer[MAX_CHARS]; - Q_ASSERT( count < MAX_CHARS ); + Q_ASSERT(count < MAX_CHARS); LineProperty currentLineProperties = 0; - //determine if the line is in the history buffer or the screen image - if (line < history->getLines()) - { + // determine if the line is in the history buffer or the screen image + if (line < history->getLines()) { const int lineLength = history->getLineLen(line); // ensure that start position is before end of line - start = qMin(start,qMax(0,lineLength-1)); + start = qMin(start, qMax(0, lineLength - 1)); // retrieve line from history buffer. It is assumed // that the history buffer does not store trailing white space // at the end of the line, so it does not need to be trimmed here - if (count == -1) - { - count = lineLength-start; - } - else - { - count = qMin(start+count,lineLength)-start; + if (count == -1) { + count = lineLength - start; + } else { + count = qMin(start + count, lineLength) - start; } // safety checks - Q_ASSERT( start >= 0 ); - Q_ASSERT( count >= 0 ); - Q_ASSERT( (start+count) <= history->getLineLen(line) ); + Q_ASSERT(start >= 0); + Q_ASSERT(count >= 0); + Q_ASSERT((start + count) <= history->getLineLen(line)); - history->getCells(line,start,count,characterBuffer); + history->getCells(line, start, count, characterBuffer); - if ( history->isWrappedLine(line) ) + if (history->isWrappedLine(line)) currentLineProperties |= LINE_WRAPPED; - } - else - { - if ( count == -1 ) + } else { + if (count == -1) count = columns - start; - Q_ASSERT( count >= 0 ); + Q_ASSERT(count >= 0); - const int screenLine = line-history->getLines(); + const int screenLine = line - history->getLines(); - Character* data = screenLines[screenLine].data(); + Character *data = screenLines[screenLine].data(); int length = screenLines[screenLine].count(); - //retrieve line from screen image - for (int i=start;i < qMin(start+count,length);i++) - { - characterBuffer[i-start] = data[i]; + // retrieve line from screen image + for (int i = start; i < qMin(start + count, length); i++) { + characterBuffer[i - start] = data[i]; } // count cannot be any greater than length - count = qBound(0,count,length>=start?length-start:0); + count = qBound(0, count, length >= start ? length - start : 0); - Q_ASSERT( screenLine < lineProperties.count() ); + Q_ASSERT(screenLine < lineProperties.count()); currentLineProperties |= lineProperties[screenLine]; } // add new line character at end - const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) || - !preserveLineBreaks; + const bool omitLineBreak = + (currentLineProperties & LINE_WRAPPED) || !preserveLineBreaks; - if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) ) - { + if (!omitLineBreak && appendNewLine && (count + 1 < MAX_CHARS)) { characterBuffer[count] = '\n'; count++; } - //decode line and write to text stream - decoder->decodeLine( (Character*) characterBuffer , - count, currentLineProperties ); + // decode line and write to text stream + decoder->decodeLine((Character *)characterBuffer, count, + currentLineProperties); return count; } -void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const -{ - writeToStream(decoder,loc(0,fromLine),loc(columns-1,toLine)); +void Screen::writeLinesToStream(TerminalCharacterDecoder *decoder, int fromLine, + int toLine) const { + writeToStream(decoder, loc(0, fromLine), loc(columns - 1, toLine)); } -void Screen::addHistLine() -{ +void Screen::addHistLine() { // add line to history buffer // we have to take care about scrolling, too... - if (hasScroll()) - { + if (hasScroll()) { int oldHistLines = history->getLines(); history->addCellsVector(screenLines[0]); - history->addLine( lineProperties[0] & LINE_WRAPPED ); + history->addLine(lineProperties[0] & LINE_WRAPPED); int newHistLines = history->getLines(); @@ -1385,23 +1232,20 @@ void Screen::addHistLine() // If the history is full, increment the count // of dropped lines - if ( newHistLines == oldHistLines ) + if (newHistLines == oldHistLines) _droppedLines++; // Adjust selection for the new point of reference - if (newHistLines > oldHistLines) - { - if (selBegin != -1) - { + if (newHistLines > oldHistLines) { + if (selBegin != -1) { selTopLeft += columns; selBottomRight += columns; } } - if (selBegin != -1) - { + if (selBegin != -1) { // Scroll selection in history up - int top_BR = loc(0, 1+newHistLines); + int top_BR = loc(0, 1 + newHistLines); if (selTopLeft < top_BR) selTopLeft -= columns; @@ -1411,8 +1255,7 @@ void Screen::addHistLine() if (selBottomRight < 0) clearSelection(); - else - { + else { if (selTopLeft < 0) selTopLeft = 0; } @@ -1425,44 +1268,32 @@ void Screen::addHistLine() } } -int Screen::getHistLines() const -{ - return history->getLines(); -} +int Screen::getHistLines() const { return history->getLines(); } -void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) -{ +void Screen::setScroll(const HistoryType &t, bool copyPreviousScroll) { clearSelection(); - if ( copyPreviousScroll ) + if (copyPreviousScroll) history = t.scroll(history); - else - { - HistoryScroll* oldScroll = history; + else { + HistoryScroll *oldScroll = history; history = t.scroll(nullptr); delete oldScroll; } } -bool Screen::hasScroll() const -{ - return history->hasScroll(); -} +bool Screen::hasScroll() const { return history->hasScroll(); } -const HistoryType& Screen::getScroll() const -{ - return history->getType(); -} +const HistoryType &Screen::getScroll() const { return history->getType(); } -void Screen::setLineProperty(LineProperty property , bool enable) -{ - if ( enable ) +void Screen::setLineProperty(LineProperty property, bool enable) { + if (enable) lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property); else lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property); } -void Screen::fillWithDefaultChar(Character* dest, int count) -{ - for (int i=0;i - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright (C) 2007 by Robert Knight + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ - #include "ScreenWindow.h" -#include #include "Screen.h" +#include -ScreenWindow::ScreenWindow(QObject* parent) - : QObject(parent) - , _screen(nullptr) - , _windowBuffer(nullptr) - , _windowBufferSize(0) - , _bufferNeedsUpdate(true) - , _windowLines(1) - , _currentLine(0) - , _trackOutput(true) - , _scrollCount(0) -{ +ScreenWindow::ScreenWindow(QObject *parent) + : QObject(parent), _screen(nullptr), _windowBuffer(nullptr), + _windowBufferSize(0), _bufferNeedsUpdate(true), _windowLines(1), + _currentLine(0), _trackOutput(true), _scrollCount(0) { } -ScreenWindow::~ScreenWindow() -{ - delete[] _windowBuffer; + +ScreenWindow::~ScreenWindow() { + delete[] _windowBuffer; } -void ScreenWindow::setScreen(Screen* screen) -{ - Q_ASSERT( screen ); - _screen = screen; +void ScreenWindow::setScreen(Screen *screen) { + Q_ASSERT(screen); + _screen = screen; } -Screen* ScreenWindow::screen() const -{ - return _screen; +Screen *ScreenWindow::screen() const { + return _screen; } -Character* ScreenWindow::getImage() -{ - // reallocate internal buffer if the window size has changed +Character *ScreenWindow::getImage() { + // reallocate internal buffer if the window size has changed int size = windowLines() * windowColumns(); - if (_windowBuffer == nullptr || _windowBufferSize != size) - { + if (_windowBuffer == nullptr || _windowBufferSize != size) { delete[] _windowBuffer; _windowBufferSize = size; _windowBuffer = new Character[size]; _bufferNeedsUpdate = true; } - if (!_bufferNeedsUpdate) + if (!_bufferNeedsUpdate) return _windowBuffer; - _screen->getImage(_windowBuffer,size, - currentLine(),endWindowLine()); + _screen->getImage(_windowBuffer, size, currentLine(), endWindowLine()); // this window may look beyond the end of the screen, in which // case there will be an unused area which needs to be filled @@ -76,15 +63,15 @@ Character* ScreenWindow::getImage() return _windowBuffer; } -void ScreenWindow::fillUnusedArea() -{ +void ScreenWindow::fillUnusedArea() { int screenEndLine = _screen->getHistLines() + _screen->getLines() - 1; int windowEndLine = currentLine() + windowLines() - 1; int unusedLines = windowEndLine - screenEndLine; int charsToFill = unusedLines * windowColumns(); - Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); + Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill, + charsToFill); } // return the index of the line at the end of this window, or if this window @@ -94,14 +81,12 @@ void ScreenWindow::fillUnusedArea() // when passing a line number to a Screen method, the line number should // never be more than endWindowLine() // -int ScreenWindow::endWindowLine() const -{ - return qMin(currentLine() + windowLines() - 1, - lineCount() - 1); +int ScreenWindow::endWindowLine() const { + return qMin(currentLine() + windowLines() - 1, lineCount() - 1); } -QVector ScreenWindow::getLineProperties() -{ - QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); + +QVector ScreenWindow::getLineProperties() { + QVector result = _screen->getLineProperties(currentLine(), endWindowLine()); if (result.count() != windowLines()) result.resize(windowLines()); @@ -109,138 +94,109 @@ QVector ScreenWindow::getLineProperties() return result; } -QString ScreenWindow::selectedText( bool preserveLineBreaks ) const -{ - return _screen->selectedText( preserveLineBreaks ); +QString ScreenWindow::selectedText(bool preserveLineBreaks) const { + return _screen->selectedText(preserveLineBreaks); } -void ScreenWindow::getSelectionStart( int& column , int& line ) -{ - _screen->getSelectionStart(column,line); +void ScreenWindow::getSelectionStart(int &column, int &line) { + _screen->getSelectionStart(column, line); line -= currentLine(); } -void ScreenWindow::getSelectionEnd( int& column , int& line ) -{ - _screen->getSelectionEnd(column,line); + +void ScreenWindow::getSelectionEnd(int &column, int &line) { + _screen->getSelectionEnd(column, line); line -= currentLine(); } -void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) -{ - _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); + +void ScreenWindow::setSelectionStart(int column, int line, bool columnMode) { + _screen->setSelectionStart(column, qMin(line + currentLine(), endWindowLine()), columnMode); _bufferNeedsUpdate = true; emit selectionChanged(); } -void ScreenWindow::setSelectionEnd( int column , int line ) -{ - _screen->setSelectionEnd( column , qMin(line + currentLine(),endWindowLine()) ); +void ScreenWindow::setSelectionEnd(int column, int line) { + _screen->setSelectionEnd(column, qMin(line + currentLine(), endWindowLine())); _bufferNeedsUpdate = true; emit selectionChanged(); } -bool ScreenWindow::isSelected( int column , int line ) -{ - return _screen->isSelected( column , qMin(line + currentLine(),endWindowLine()) ); +bool ScreenWindow::isSelected(int column, int line) { + return _screen->isSelected(column, qMin(line + currentLine(), endWindowLine())); } -void ScreenWindow::clearSelection() -{ +void ScreenWindow::clearSelection() { _screen->clearSelection(); emit selectionChanged(); } -bool ScreenWindow::isClearSelection() -{ - return _screen->isClearSelection(); +bool ScreenWindow::isClearSelection() { + return _screen->isClearSelection(); } -void ScreenWindow::setWindowLines(int lines) -{ +void ScreenWindow::setWindowLines(int lines) { Q_ASSERT(lines > 0); _windowLines = lines; } -int ScreenWindow::windowLines() const -{ - return _windowLines; + +int ScreenWindow::windowLines() const { + return _windowLines; } -int ScreenWindow::windowColumns() const -{ - return _screen->getColumns(); +int ScreenWindow::windowColumns() const { + return _screen->getColumns(); } -int ScreenWindow::lineCount() const -{ +int ScreenWindow::lineCount() const { return _screen->getHistLines() + _screen->getLines(); } -int ScreenWindow::columnCount() const -{ - return _screen->getColumns(); +int ScreenWindow::columnCount() const { + return _screen->getColumns(); } -QPoint ScreenWindow::cursorPosition() const -{ +QPoint ScreenWindow::cursorPosition() const { QPoint position; - position.setX( _screen->getCursorX() ); - position.setY( _screen->getCursorY() ); + position.setX(_screen->getCursorX()); + position.setY(_screen->getCursorY()); return position; } -int ScreenWindow::getCursorX() const { - return _screen->getCursorX(); -} - -int ScreenWindow::getCursorY() const { - return _screen->getCursorY(); -} - -void ScreenWindow::setCursorX(int x) { - _screen->setCursorX(x); -} - -void ScreenWindow::setCursorY(int y) { - _screen->setCursorY(y); -} +int ScreenWindow::getCursorX() const { return _screen->getCursorX(); } +int ScreenWindow::getCursorY() const { return _screen->getCursorY(); } +void ScreenWindow::setCursorX(int x) { _screen->setCursorX(x); } +void ScreenWindow::setCursorY(int y) { _screen->setCursorY(y); } QString ScreenWindow::getScreenText(int row1, int col1, int row2, int col2, int mode) { - return _screen->getScreenText( row1, col1, row2, col2, mode ); + return _screen->getScreenText(row1, col1, row2, col2, mode); } -int ScreenWindow::currentLine() const -{ - if(lineCount()>=windowLines()) { - return qBound(0,_currentLine,lineCount()-windowLines()); +int ScreenWindow::currentLine() const { + if (lineCount() >= windowLines()) { + return qBound(0, _currentLine, lineCount() - windowLines()); } return 0; } -void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) -{ - if ( mode == ScrollLines ) - { - scrollTo( currentLine() + amount ); - } - else if ( mode == ScrollPages ) - { - scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); +void ScreenWindow::scrollBy(RelativeScrollMode mode, int amount) { + if (mode == ScrollLines) { + scrollTo(currentLine() + amount); + } else if (mode == ScrollPages) { + scrollTo(currentLine() + amount * (windowLines() / 2)); } } -bool ScreenWindow::atEndOfOutput() const -{ - return currentLine() == (lineCount()-windowLines()); +bool ScreenWindow::atEndOfOutput() const { + return currentLine() == (lineCount() - windowLines()); } -void ScreenWindow::scrollTo( int line ) -{ +void ScreenWindow::scrollTo(int line) { int maxCurrentLineNumber = lineCount() - windowLines(); - line = qBound(0,line,maxCurrentLineNumber); + line = qBound(0, line, maxCurrentLineNumber); const int delta = line - _currentLine; _currentLine = line; @@ -254,58 +210,41 @@ void ScreenWindow::scrollTo( int line ) emit scrolled(_currentLine); } -void ScreenWindow::setTrackOutput(bool trackOutput) -{ +void ScreenWindow::setTrackOutput(bool trackOutput) { _trackOutput = trackOutput; } -bool ScreenWindow::trackOutput() const -{ - return _trackOutput; -} +bool ScreenWindow::trackOutput() const { return _trackOutput; } +int ScreenWindow::scrollCount() const { return _scrollCount; } +void ScreenWindow::resetScrollCount() { _scrollCount = 0; } -int ScreenWindow::scrollCount() const -{ - return _scrollCount; -} - -void ScreenWindow::resetScrollCount() -{ - _scrollCount = 0; -} - -QRect ScreenWindow::scrollRegion() const -{ +QRect ScreenWindow::scrollRegion() const { bool equalToScreenSize = windowLines() == _screen->getLines(); - if ( atEndOfOutput() && equalToScreenSize ) + if (atEndOfOutput() && equalToScreenSize) return _screen->lastScrolledRegion(); else - return {0,0,windowColumns(),windowLines()}; + return {0, 0, windowColumns(), windowLines()}; } -void ScreenWindow::notifyOutputChanged() -{ +void ScreenWindow::notifyOutputChanged() { // move window to the bottom of the screen and update scroll count // if this window is currently tracking the bottom of the screen - if ( _trackOutput ) - { + if (_trackOutput) { _scrollCount -= _screen->scrolledLines(); - _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); - } - else - { + _currentLine = qMax(0, _screen->getHistLines() - + (windowLines() - _screen->getLines())); + } else { // if the history is not unlimited then it may // have run out of space and dropped the oldest // lines of output - in this case the screen // window's current line number will need to // be adjusted - otherwise the output will scroll - _currentLine = qMax(0,_currentLine - - _screen->droppedLines()); + _currentLine = qMax(0, _currentLine - _screen->droppedLines()); // ensure that the screen window's current position does // not go beyond the bottom of the screen - _currentLine = qMin( _currentLine , _screen->getHistLines() ); + _currentLine = qMin(_currentLine, _screen->getHistLines()); } _bufferNeedsUpdate = true; @@ -313,49 +252,42 @@ void ScreenWindow::notifyOutputChanged() emit outputChanged(); } -void ScreenWindow::handleCommandFromKeyboard(KeyboardTranslator::Command command) -{ +void ScreenWindow::handleCommandFromKeyboard( + KeyboardTranslator::Command command) { // Keyboard-based navigation bool update = false; // EraseCommand is handled in Vt102Emulation - if ( command & KeyboardTranslator::ScrollPageUpCommand ) - { - scrollBy( ScreenWindow::ScrollPages , -1 ); + if (command & KeyboardTranslator::ScrollPageUpCommand) { + scrollBy(ScreenWindow::ScrollPages, -1); update = true; } - if ( command & KeyboardTranslator::ScrollPageDownCommand ) - { - scrollBy( ScreenWindow::ScrollPages , 1 ); + if (command & KeyboardTranslator::ScrollPageDownCommand) { + scrollBy(ScreenWindow::ScrollPages, 1); update = true; } - if ( command & KeyboardTranslator::ScrollLineUpCommand ) - { - scrollBy( ScreenWindow::ScrollLines , -1 ); + if (command & KeyboardTranslator::ScrollLineUpCommand) { + scrollBy(ScreenWindow::ScrollLines, -1); update = true; } - if ( command & KeyboardTranslator::ScrollLineDownCommand ) - { - scrollBy( ScreenWindow::ScrollLines , 1 ); + if (command & KeyboardTranslator::ScrollLineDownCommand) { + scrollBy(ScreenWindow::ScrollLines, 1); update = true; } - if ( command & KeyboardTranslator::ScrollDownToBottomCommand ) - { - Q_EMIT scrollToEnd(); + if (command & KeyboardTranslator::ScrollDownToBottomCommand) { + emit scrollToEnd(); update = true; } - if ( command & KeyboardTranslator::ScrollUpToTopCommand) - { + if (command & KeyboardTranslator::ScrollUpToTopCommand) { scrollTo(0); update = true; } // TODO: KeyboardTranslator::ScrollLockCommand // TODO: KeyboardTranslator::SendCommand - if ( update ) - { - setTrackOutput( atEndOfOutput() ); + if (update) { + setTrackOutput(atEndOfOutput()); - Q_EMIT outputChanged(); + emit outputChanged(); } } diff --git a/lib/qtermwidget/ScreenWindow.h b/lib/qtermwidget/ScreenWindow.h index 0921a34d..5b1e2768 100644 --- a/lib/qtermwidget/ScreenWindow.h +++ b/lib/qtermwidget/ScreenWindow.h @@ -1,20 +1,20 @@ /* - Copyright 2007-2008 by Robert Knight - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2007-2008 by Robert Knight + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef SCREENWINDOW_H @@ -48,8 +48,7 @@ class Screen; */ class ScreenWindow : public QObject { -Q_OBJECT - + Q_OBJECT public: /** * Constructs a new screen window with the given parent. @@ -174,8 +173,7 @@ Q_OBJECT void scrollTo( int line ); /** Describes the units which scrollBy() moves the window by. */ - enum RelativeScrollMode - { + enum RelativeScrollMode { /** Scroll the window down by a given number of lines. */ ScrollLines, /** diff --git a/lib/qtermwidget/SearchBar.cpp b/lib/qtermwidget/SearchBar.cpp index b1f2125d..c50ff0da 100644 --- a/lib/qtermwidget/SearchBar.cpp +++ b/lib/qtermwidget/SearchBar.cpp @@ -1,20 +1,20 @@ /* - Copyright 2013 Christian Surlykke - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2013 Christian Surlykke + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include #include @@ -24,11 +24,10 @@ #include "SearchBar.h" #include "qfonticon.h" -SearchBar::SearchBar(QWidget *parent) : QWidget(parent) -{ +SearchBar::SearchBar(QWidget *parent) : QWidget(parent) { widget.setupUi(this); setAutoFillBackground(true); // make it always opaque, especially inside translucent windows - + connect(widget.closeButton, &QToolButton::clicked, this, &SearchBar::hide); connect(widget.searchTextEdit, &QLineEdit::textChanged, this, &SearchBar::searchCriteriaChanged); connect(widget.findPreviousButton, &QToolButton::clicked, this, &SearchBar::findPrevious); @@ -44,7 +43,6 @@ SearchBar::SearchBar(QWidget *parent) : QWidget(parent) m_matchCaseMenuEntry->setChecked(true); connect(m_matchCaseMenuEntry, &QAction::toggled, this, &SearchBar::searchCriteriaChanged); - m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression")); m_useRegularExpressionMenuEntry->setCheckable(true); connect(m_useRegularExpressionMenuEntry, &QAction::toggled, this, &SearchBar::searchCriteriaChanged); @@ -60,36 +58,30 @@ SearchBar::SearchBar(QWidget *parent) : QWidget(parent) SearchBar::~SearchBar() { } -QString SearchBar::searchText() -{ +QString SearchBar::searchText() { return widget.searchTextEdit->text(); } -bool SearchBar::useRegularExpression() -{ +bool SearchBar::useRegularExpression() { return m_useRegularExpressionMenuEntry->isChecked(); } -bool SearchBar::matchCase() -{ +bool SearchBar::matchCase() { return m_matchCaseMenuEntry->isChecked(); } -bool SearchBar::highlightAllMatches() -{ +bool SearchBar::highlightAllMatches() { return m_highlightMatchesMenuEntry->isChecked(); } -void SearchBar::show() -{ +void SearchBar::show() { QWidget::show(); widget.searchTextEdit->setFocus(); widget.searchTextEdit->selectAll(); } -void SearchBar::hide() -{ +void SearchBar::hide() { QWidget::hide(); if (QWidget *p = parentWidget()) { @@ -97,40 +89,29 @@ void SearchBar::hide() } } -void SearchBar::noMatchFound() -{ +void SearchBar::noMatchFound() { QPalette palette; palette.setColor(widget.searchTextEdit->backgroundRole(), QColor(255, 128, 128)); widget.searchTextEdit->setPalette(palette); } - -void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) -{ - if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) - { - if (keyEvent->modifiers() == Qt::ShiftModifier) - { - Q_EMIT findPrevious(); +void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) { + if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { + if (keyEvent->modifiers() == Qt::ShiftModifier) { + emit findPrevious(); + } else { + emit findNext(); } - else - { - Q_EMIT findNext(); - } - } - else if (keyEvent->key() == Qt::Key_Escape) - { + } else if (keyEvent->key() == Qt::Key_Escape) { hide(); } } -void SearchBar::clearBackgroundColor() -{ +void SearchBar::clearBackgroundColor() { widget.searchTextEdit->setPalette(QWidget::window()->palette()); } -void SearchBar::setText(const QString &text) -{ +void SearchBar::setText(const QString &text) { return widget.searchTextEdit->setText(text); } diff --git a/lib/qtermwidget/SearchBar.h b/lib/qtermwidget/SearchBar.h index 9896af2c..3358c35f 100644 --- a/lib/qtermwidget/SearchBar.h +++ b/lib/qtermwidget/SearchBar.h @@ -1,20 +1,20 @@ /* - Copyright 2013 Christian Surlykke - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2013 Christian Surlykke + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef _SEARCHBAR_H #define _SEARCHBAR_H diff --git a/lib/qtermwidget/TerminalCharacterDecoder.cpp b/lib/qtermwidget/TerminalCharacterDecoder.cpp index d067622c..cacd80bf 100644 --- a/lib/qtermwidget/TerminalCharacterDecoder.cpp +++ b/lib/qtermwidget/TerminalCharacterDecoder.cpp @@ -1,84 +1,80 @@ /* - This file is part of Konsole, an X terminal. + This file is part of Konsole, an X terminal. - Copyright 2006-2008 by Robert Knight + Copyright 2006-2008 by Robert Knight - This program 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 of the License, or - (at your option) any later version. + This program 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 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. + 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 Lesser General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "TerminalCharacterDecoder.h" -#include #include "CharWidth.h" +#include #include PlainTextDecoder::PlainTextDecoder() - : _output(nullptr) - , _includeTrailingWhitespace(true) - , _recordLinePositions(false) -{ + : _output(nullptr), _includeTrailingWhitespace(true), + _recordLinePositions(false) { } -void PlainTextDecoder::setTrailingWhitespace(bool enable) -{ + +void PlainTextDecoder::setTrailingWhitespace(bool enable) { _includeTrailingWhitespace = enable; } -bool PlainTextDecoder::trailingWhitespace() const -{ + +bool PlainTextDecoder::trailingWhitespace() const { return _includeTrailingWhitespace; } -void PlainTextDecoder::begin(QTextStream* output) -{ - _output = output; - if (!_linePositions.isEmpty()) - _linePositions.clear(); + +void PlainTextDecoder::begin(QTextStream *output) { + _output = output; + if (!_linePositions.isEmpty()) + _linePositions.clear(); } -void PlainTextDecoder::end() -{ - _output = nullptr; + +void PlainTextDecoder::end() { + _output = nullptr; } -void PlainTextDecoder::setRecordLinePositions(bool record) -{ +void PlainTextDecoder::setRecordLinePositions(bool record) { _recordLinePositions = record; } -QList PlainTextDecoder::linePositions() const -{ - return _linePositions; + +QList PlainTextDecoder::linePositions() const { + return _linePositions; } -void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ - ) -{ - Q_ASSERT( _output ); - if (_recordLinePositions && _output->string()) - { +void PlainTextDecoder::decodeLine(const Character *const characters, int count, + LineProperty /*properties*/) { + Q_ASSERT(_output); + + if (_recordLinePositions && _output->string()) { int pos = _output->string()->size(); _linePositions << pos; } - if (characters == nullptr) - { - // TODO: So far, this has happened only under kwin_wayland, when the current function - // is called by TerminalDisplay::inputMethodQuery(). The actual issue should be found. + if (characters == nullptr) { + // TODO: So far, this has happened only under kwin_wayland, when the current + // function is called by TerminalDisplay::inputMethodQuery(). The actual + // issue should be found. return; } - //TODO should we ignore or respect the LINE_WRAPPED line property? + // TODO should we ignore or respect the LINE_WRAPPED line property? - //note: we build up a QString and send it to the text stream rather writing into the text - //stream a character at a time because it is more efficient. + // note: we build up a QString and send it to the text stream rather writing + // into the text stream a character at a time because it is more efficient. //(since QTextStream always deals with QStrings internally anyway) std::wstring plainText; plainText.reserve(count); @@ -87,48 +83,42 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, // if inclusion of trailing whitespace is disabled then find the end of the // line - if ( !_includeTrailingWhitespace ) - { - for (int i = count-1 ; i >= 0 ; i--) - { - if ( characters[i].character != L' ' ) + if (!_includeTrailingWhitespace) { + for (int i = count - 1; i >= 0; i--) { + if (characters[i].character != L' ') break; else outputCount--; } } - for (int i=0;i') - text.append(L">"); + text.append(L">"); else - text.push_back(ch); - } - else - { - text.append(L" "); //HTML truncates multiple spaces, so use a space marker instead + text.push_back(ch); + } else { + text.append(L" "); // HTML truncates multiple spaces, so use a space + // marker instead } } - //close any remaining open inner spans - if ( _innerSpanOpen ) + // close any remaining open inner spans + if (_innerSpanOpen) closeSpan(text); - //start new line + // start new line text.append(L"
"); *_output << QString::fromStdWString(text); } -void HTMLDecoder::openSpan(std::wstring& text , const QString& style) -{ - text.append( QString(QLatin1String("")).arg(style).toStdWString() ); + +void HTMLDecoder::openSpan(std::wstring &text, const QString &style) { + text.append(QString(QLatin1String("")).arg(style).toStdWString()); } -void HTMLDecoder::closeSpan(std::wstring& text) -{ - text.append(L""); +void HTMLDecoder::closeSpan(std::wstring &text) { + text.append(L""); } -void HTMLDecoder::setColorTable(const ColorEntry* table) -{ +void HTMLDecoder::setColorTable(const ColorEntry *table) { _colorTable = table; } diff --git a/lib/qtermwidget/TerminalCharacterDecoder.h b/lib/qtermwidget/TerminalCharacterDecoder.h index e25e996e..2011121f 100644 --- a/lib/qtermwidget/TerminalCharacterDecoder.h +++ b/lib/qtermwidget/TerminalCharacterDecoder.h @@ -1,22 +1,22 @@ /* - This file is part of Konsole, an X terminal. - - Copyright 2006-2008 by Robert Knight - - This program 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 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 Lesser General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + + Copyright 2006-2008 by Robert Knight + + This program 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 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 Lesser General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef TERMINAL_CHARACTER_DECODER_H diff --git a/lib/qtermwidget/TerminalDisplay.cpp b/lib/qtermwidget/TerminalDisplay.cpp index 196f4384..1529ca03 100644 --- a/lib/qtermwidget/TerminalDisplay.cpp +++ b/lib/qtermwidget/TerminalDisplay.cpp @@ -1,23 +1,23 @@ /* - This file is part of Konsole, a terminal emulator for KDE. + This file is part of Konsole, a terminal emulator for KDE. - Copyright 2006-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle + Copyright 2006-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle - 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 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. + 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "TerminalDisplay.h" @@ -25,62 +25,73 @@ #include #include #include -#include +#include #include -#include #include #include +#include #include #include +#include #include +#include +#include #include #include #include #include #include +#include #include -#include +#include #include -#include -#include -#include -#include -#include #include -#include +#include +#include #include "Filter.h" #include "ScreenWindow.h" #include "TerminalCharacterDecoder.h" #ifndef loc -#define loc(X,Y) ((Y)*_columns+(X)) +#define loc(X, Y) ((Y) * _columns + (X)) #endif #define yMouseScroll 1 -#define REPCHAR "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ - "abcdefgjijklmnopqrstuvwxyz" \ - "0123456789./+@" +#define REPCHAR \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ + "abcdefgjijklmnopqrstuvwxyz" \ + "0123456789./+@" const ColorEntry base_color_table[TABLE_COLORS] = // The following are almost IBM standard color codes, with some slight // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { - // Fixme: could add faint colors here, also. - // normal - ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0xB2,0xB2), true), // Dfore, Dback - ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0x18,0x18), false), // Black, Red - ColorEntry(QColor(0x18,0xB2,0x18), false), ColorEntry( QColor(0xB2,0x68,0x18), false), // Green, Yellow - ColorEntry(QColor(0x18,0x18,0xB2), false), ColorEntry( QColor(0xB2,0x18,0xB2), false), // Blue, Magenta - ColorEntry(QColor(0x18,0xB2,0xB2), false), ColorEntry( QColor(0xB2,0xB2,0xB2), false), // Cyan, White - // intensiv - ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true), - ColorEntry(QColor(0x68,0x68,0x68), false), ColorEntry( QColor(0xFF,0x54,0x54), false), - ColorEntry(QColor(0x54,0xFF,0x54), false), ColorEntry( QColor(0xFF,0xFF,0x54), false), - ColorEntry(QColor(0x54,0x54,0xFF), false), ColorEntry( QColor(0xFF,0x54,0xFF), false), - ColorEntry(QColor(0x54,0xFF,0xFF), false), ColorEntry( QColor(0xFF,0xFF,0xFF), false) + // Fixme: could add faint colors here, also. + // normal + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xB2, 0xB2, 0xB2), true), // Dfore, Dback + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xB2, 0x18, 0x18), false), // Black, Red + ColorEntry(QColor(0x18, 0xB2, 0x18), false), + ColorEntry(QColor(0xB2, 0x68, 0x18), false), // Green, Yellow + ColorEntry(QColor(0x18, 0x18, 0xB2), false), + ColorEntry(QColor(0xB2, 0x18, 0xB2), false), // Blue, Magenta + ColorEntry(QColor(0x18, 0xB2, 0xB2), false), + ColorEntry(QColor(0xB2, 0xB2, 0xB2), false), // Cyan, White + // intensiv + ColorEntry(QColor(0x00, 0x00, 0x00), false), + ColorEntry(QColor(0xFF, 0xFF, 0xFF), true), + ColorEntry(QColor(0x68, 0x68, 0x68), false), + ColorEntry(QColor(0xFF, 0x54, 0x54), false), + ColorEntry(QColor(0x54, 0xFF, 0x54), false), + ColorEntry(QColor(0xFF, 0xFF, 0x54), false), + ColorEntry(QColor(0x54, 0x54, 0xFF), false), + ColorEntry(QColor(0xFF, 0x54, 0xFF), false), + ColorEntry(QColor(0x54, 0xFF, 0xFF), false), + ColorEntry(QColor(0xFF, 0xFF, 0xFF), false) }; // scroll increment used when dragging selection at top/bottom of window. @@ -91,7 +102,7 @@ bool TerminalDisplay::HAVE_TRANSPARENCY = true; // we use this to force QPainter to display text in LTR mode // more information can be found in: http://unicode.org/reports/tr9/ -const QChar LTR_OVERRIDE_CHAR( 0x202D ); +const QChar LTR_OVERRIDE_CHAR(0x202D); /* ------------------------------------------------------------------------- */ /* */ @@ -99,77 +110,73 @@ const QChar LTR_OVERRIDE_CHAR( 0x202D ); /* */ /* ------------------------------------------------------------------------- */ -/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) +/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) - Code 0 1 2 3 4 5 6 7 - ----------- ------- ------- ------- ------- ------- ------- ------- ------- - ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White - IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White + Code 0 1 2 3 4 5 6 7 + ----------- ------- ------- ------- ------- ------- ------- ------- ------- + ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White + IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ -ScreenWindow* TerminalDisplay::screenWindow() const -{ - return _screenWindow; -} -void TerminalDisplay::setScreenWindow(ScreenWindow* window) -{ +ScreenWindow *TerminalDisplay::screenWindow() const { return _screenWindow; } +void TerminalDisplay::setScreenWindow(ScreenWindow *window) { // disconnect existing screen window if any - if ( _screenWindow ) - { - disconnect( _screenWindow , nullptr , this , nullptr ); + if (_screenWindow) { + disconnect(_screenWindow, nullptr, this, nullptr); } _screenWindow = window; - if ( window ) - { -// TODO: Determine if this is an issue. -//#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?" - connect( _screenWindow , &ScreenWindow::outputChanged , this , &TerminalDisplay::updateLineProperties ); - connect( _screenWindow , &ScreenWindow::outputChanged , this , &TerminalDisplay::updateImage ); - connect( _screenWindow , &ScreenWindow::outputChanged , this , &TerminalDisplay::updateFilters ); - connect( _screenWindow , &ScreenWindow::scrolled , this , &TerminalDisplay::updateFilters ); - connect( _screenWindow , &ScreenWindow::scrollToEnd , this , &TerminalDisplay::scrollToEnd ); - connect( _screenWindow , &ScreenWindow::handleCtrlC , this , &TerminalDisplay::handleCtrlC ); + if (window) { + // TODO: Determine if this is an issue. + // #warning "The order here is not specified - does it matter whether + // updateImage or updateLineProperties comes first?" + connect(_screenWindow, &ScreenWindow::outputChanged, this, + &TerminalDisplay::updateLineProperties); + connect(_screenWindow, &ScreenWindow::outputChanged, this, + &TerminalDisplay::updateImage); + connect(_screenWindow, &ScreenWindow::outputChanged, this, + &TerminalDisplay::updateFilters); + connect(_screenWindow, &ScreenWindow::scrolled, this, + &TerminalDisplay::updateFilters); + connect(_screenWindow, &ScreenWindow::scrollToEnd, this, + &TerminalDisplay::scrollToEnd); + connect(_screenWindow, &ScreenWindow::handleCtrlC, this, + &TerminalDisplay::handleCtrlC); window->setWindowLines(_lines); } } -const ColorEntry* TerminalDisplay::colorTable() const -{ - return _colorTable; -} -void TerminalDisplay::setBackgroundColor(const QColor& color) -{ +const ColorEntry *TerminalDisplay::colorTable() const { return _colorTable; } + +void TerminalDisplay::setBackgroundColor(const QColor &color) { _colorTable[DEFAULT_BACK_COLOR].color = color; QPalette p = palette(); - p.setColor( backgroundRole(), color ); - setPalette( p ); + p.setColor(backgroundRole(), color); + setPalette(p); - // Avoid propagating the palette change to the scroll bar - _scrollBar->setPalette( QApplication::palette() ); + // Avoid propagating the palette change to the scroll bar + _scrollBar->setPalette(QApplication::palette()); update(); } -void TerminalDisplay::setForegroundColor(const QColor& color) -{ + +void TerminalDisplay::setForegroundColor(const QColor &color) { _colorTable[DEFAULT_FORE_COLOR].color = color; update(); } -void TerminalDisplay::setColorTableColor(const int colorId, const QColor &color) -{ +void TerminalDisplay::setColorTableColor(const int colorId, const QColor &color) { _colorTable[colorId].color = color; update(); } -void TerminalDisplay::setColorTable(const ColorEntry table[]) -{ - for (int i = 0; i < TABLE_COLORS; i++) - _colorTable[i] = table[i]; +void TerminalDisplay::setColorTable(const ColorEntry table[]) { + for (int i = 0; i < TABLE_COLORS; i++) + _colorTable[i] = table[i]; - setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); + setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); } /* ------------------------------------------------------------------------- */ @@ -179,127 +186,113 @@ void TerminalDisplay::setColorTable(const ColorEntry table[]) /* ------------------------------------------------------------------------- */ /* - The VT100 has 32 special graphical characters. The usual vt100 extended - xterm fonts have these at 0x00..0x1f. - - QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals - come in here as proper unicode characters. - - We treat non-iso10646 fonts as VT100 extended and do the required mapping - from unicode to 0x00..0x1f. The remaining translation is then left to the - QCodec. + The VT100 has 32 special graphical characters. The usual vt100 extended + xterm fonts have these at 0x00..0x1f. + + QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals + come in here as proper unicode characters. + + We treat non-iso10646 fonts as VT100 extended and do the required mapping + from unicode to 0x00..0x1f. The remaining translation is then left to the + QCodec. */ bool TerminalDisplay::isLineChar(wchar_t c) const { return _drawLineChars && ((c & 0xFF80) == 0x2500); } -bool TerminalDisplay::isLineCharString(const std::wstring& string) const { +bool TerminalDisplay::isLineCharString(const std::wstring &string) const { return (string.length() > 0) && (isLineChar(string[0])); } +void TerminalDisplay::fontChange(const QFont &) { + QFontMetrics fm(font()); + _fontHeight = fm.height() + _lineSpacing; -// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. - -unsigned short vt100_graphics[32] = -{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 - 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, - 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, - 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, - 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 -}; - -void TerminalDisplay::fontChange(const QFont&) -{ - QFontMetrics fm(font()); - _fontHeight = fm.height() + _lineSpacing; - - // waba TerminalDisplay 1.123: - // "Base character width on widest ASCII character. This prevents too wide - // characters in the presence of double wide (e.g. Japanese) characters." - // Get the width from representative normal width characters - _fontWidth = qRound((double)fm.horizontalAdvance(QLatin1String(REPCHAR))/(double)qstrlen(REPCHAR)); + // waba TerminalDisplay 1.123: + // "Base character width on widest ASCII character. This prevents too wide + // characters in the presence of double wide (e.g. Japanese) characters." + // Get the width from representative normal width characters + _fontWidth = qRound((double)fm.horizontalAdvance(QLatin1String(REPCHAR)) / + (double)qstrlen(REPCHAR)); - _fixedFont = true; + _fixedFont = true; - int fw = fm.horizontalAdvance(QLatin1Char(REPCHAR[0])); - for(unsigned int i=1; i< qstrlen(REPCHAR); i++) - { - if (fw != fm.horizontalAdvance(QLatin1Char(REPCHAR[i]))) - { - _fixedFont = false; - break; + int fw = fm.horizontalAdvance(QLatin1Char(REPCHAR[0])); + for (unsigned int i = 1; i < qstrlen(REPCHAR); i++) { + if (fw != fm.horizontalAdvance(QLatin1Char(REPCHAR[i]))) { + _fixedFont = false; + break; + } } - } - if (_fontWidth < 1) - _fontWidth=1; + if (_fontWidth < 1) + _fontWidth = 1; - _fontAscent = fm.ascent(); + _fontAscent = fm.ascent(); - emit changedFontMetricSignal( _fontHeight, _fontWidth ); - propagateSize(); + emit changedFontMetricSignal(_fontHeight, _fontWidth); + propagateSize(); - // We will run paint event testing procedure. - // Although this operation will destroy the original content, - // the content will be drawn again after the test. - _drawTextTestFlag = true; - update(); + // We will run paint event testing procedure. + // Although this operation will destroy the original content, + // the content will be drawn again after the test. + _drawTextTestFlag = true; + update(); } -void TerminalDisplay::calDrawTextAdditionHeight(QPainter& painter) -{ +void TerminalDisplay::calDrawTextAdditionHeight(QPainter &painter) { QRect test_rect, feedback_rect; - test_rect.setRect(1, 1, _fontWidth * 4, _fontHeight); - painter.drawText(test_rect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QLatin1String("Mq"), &feedback_rect); + test_rect.setRect(1, 1, _fontWidth * 4, _fontHeight); + painter.drawText(test_rect, Qt::AlignBottom, + LTR_OVERRIDE_CHAR + QLatin1String("Mq"), &feedback_rect); - //qDebug() << "test_rect:" << test_rect << "feeback_rect:" << feedback_rect; + // qDebug() << "test_rect:" << test_rect << "feeback_rect:" << feedback_rect; - _drawTextAdditionHeight = (feedback_rect.height() - _fontHeight) / 2; - if(_drawTextAdditionHeight < 0) { - _drawTextAdditionHeight = 0; - } + _drawTextAdditionHeight = (feedback_rect.height() - _fontHeight) / 2; + if (_drawTextAdditionHeight < 0) { + _drawTextAdditionHeight = 0; + } - _drawTextTestFlag = false; + _drawTextTestFlag = false; } -void TerminalDisplay::setVTFont(const QFont& f) -{ - QFont font = f; +void TerminalDisplay::setVTFont(const QFont &f) { + QFont font = f; - // Check if font is not fixed pitch and print a warning - if (!QFontInfo(font).fixedPitch()) - { - //qDebug() << "Using a variable-width font in the terminal. This may cause performance degradation and display/alignment errors."; - } + // Check if font is not fixed pitch and print a warning + if (!QFontInfo(font).fixedPitch()) { + // qDebug() << "Using a variable-width font in the terminal. This may cause + // performance degradation and display/alignment errors."; + } - // hint that text should be drawn without anti-aliasing. - // depending on the user's font configuration, this may not be respected - if (!_antialiasText) - font.setStyleStrategy( QFont::NoAntialias ); + // hint that text should be drawn without anti-aliasing. + // depending on the user's font configuration, this may not be respected + if (!_antialiasText) + font.setStyleStrategy(QFont::NoAntialias); - // experimental optimization. Konsole assumes that the terminal is using a - // mono-spaced font, in which case kerning information should have no effect. - // Disabling kerning saves some computation when rendering text. - font.setKerning(false); + // experimental optimization. Konsole assumes that the terminal is using a + // mono-spaced font, in which case kerning information should have no effect. + // Disabling kerning saves some computation when rendering text. + font.setKerning(false); - // QFont::ForceIntegerMetrics has been removed. - // Set full hinting instead to ensure the letters are aligned properly. - font.setHintingPreference(QFont::PreferFullHinting); + // QFont::ForceIntegerMetrics has been removed. + // Set full hinting instead to ensure the letters are aligned properly. + font.setHintingPreference(QFont::PreferFullHinting); - // "Draw intense colors in bold font" feature needs to use different font weights. StyleName - // property, when set, doesn't allow weight changes. Since all properties (weight, stretch, - // italic, etc) are stored in QFont independently, in almost all cases styleName is not needed. - font.setStyleName(QString()); + // "Draw intense colors in bold font" feature needs to use different font + // weights. StyleName property, when set, doesn't allow weight changes. Since + // all properties (weight, stretch, italic, etc) are stored in QFont + // independently, in almost all cases styleName is not needed. + font.setStyleName(QString()); - QWidget::setFont(font); - _charWidth->setFont(font); - fontChange(font); + QWidget::setFont(font); + _charWidth->setFont(font); + fontChange(font); } -void TerminalDisplay::setFont(const QFont &) -{ - // ignore font change request if not coming from konsole itself +void TerminalDisplay::setFont(const QFont &) { + // ignore font change request if not coming from konsole itself } /* ------------------------------------------------------------------------- */ @@ -309,164 +302,135 @@ void TerminalDisplay::setFont(const QFont &) /* ------------------------------------------------------------------------- */ TerminalDisplay::TerminalDisplay(QWidget *parent) -:QWidget(parent) -,_screenWindow(nullptr) -,_allowBell(true) -,_gridLayout(nullptr) -,_fontHeight(1) -,_fontWidth(1) -,_fontAscent(1) -,_boldIntense(true) -,_lines(1) -,_columns(1) -,_usedLines(1) -,_usedColumns(1) -,_contentHeight(1) -,_contentWidth(1) -,_image(nullptr) -,_resizing(false) -,_terminalSizeHint(false) -,_terminalSizeStartup(true) -,_bidiEnabled(true) -,_mouseMarks(false) -,_isPrimaryScreen(true) -,_disabledBracketedPasteMode(false) -,_showResizeNotificationEnabled(true) -,_actSel(0) -,_wordSelectionMode(false) -,_lineSelectionMode(false) -,_preserveLineBreaks(false) -,_columnSelectionMode(false) -,_scrollbarLocation(QTermWidget::NoScrollBar) -,_wordCharacters(QLatin1String(":@-./_~")) -,_bellMode(SystemBeepBell) -,_blinking(false) -,_hasBlinker(false) -,_cursorBlinking(false) -,_hasBlinkingCursor(false) -,_allowBlinkingText(true) -,_ctrlDrag(false) -,_tripleClickMode(SelectWholeLine) -,_isFixedSize(false) -,_possibleTripleClick(false) -,_resizeWidget(nullptr) -,_resizeTimer(nullptr) -,_flowControlWarningEnabled(false) -,_outputSuspendedLabel(nullptr) -,_lineSpacing(0) -,_colorsInverted(false) -,_opacity(static_cast(1)) -,_backgroundMode(None) -,_selectedTextOpacity(static_cast(1)) -,_filterChain(new TerminalImageFilterChain()) -,_cursorShape(Emulation::KeyboardCursorShape::BlockCursor) -,mMotionAfterPasting(NoMoveScreenWindow) -,_leftBaseMargin(1) -,_topBaseMargin(1) -,_drawLineChars(true) -{ - // variables for draw text - _drawTextAdditionHeight = 0; - _drawTextTestFlag = false; - - // terminal applications are not designed with Right-To-Left in mind, - // so the layout is forced to Left-To-Right - setLayoutDirection(Qt::LeftToRight); - - // The offsets are not yet calculated. - // Do not calculate these too often to be more smoothly when resizing - // konsole in opaque mode. - _topMargin = _topBaseMargin; - _leftMargin = _leftBaseMargin; - - // create scroll bar for scrolling output up and down - // set the scroll bar's slider to occupy the whole area of the scroll bar initially - _scrollBar = new QScrollBar(this); - QString style_sheet = qApp->styleSheet(); - _scrollBar->setStyleSheet(style_sheet); - // since the contrast with the terminal background may not be enough, - // the scrollbar should be auto-filled if not transient - if (!_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) - _scrollBar->setAutoFillBackground(true); - setScroll(0,0); - _scrollBar->setCursor( Qt::ArrowCursor ); - connect(_scrollBar, &QScrollBar::valueChanged, this, &TerminalDisplay::scrollBarPositionChanged); - // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar - // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) - _scrollBar->hide(); - - // setup timers for blinking cursor and text - _blinkTimer = new QTimer(this); - connect(_blinkTimer, &QTimer::timeout, this, &TerminalDisplay::blinkEvent); - _blinkCursorTimer = new QTimer(this); - connect(_blinkCursorTimer, &QTimer::timeout, this, &TerminalDisplay::blinkCursorEvent); - -// KCursor::setAutoHideCursor( this, true ); - - setUsesMouse(true); - setBracketedPasteMode(false); - setColorTable(base_color_table); - setMouseTracking(true); - - // Enable drag and drop - setAcceptDrops(true); // attempt - dragInfo.state = diNone; - - setFocusPolicy( Qt::WheelFocus ); - - // enable input method support - setAttribute(Qt::WA_InputMethodEnabled, true); - setInputMethodHints(Qt::ImhSensitiveData|Qt::ImhNoAutoUppercase|Qt::ImhNoPredictiveText|Qt::ImhMultiLine); - - // this is an important optimization, it tells Qt - // that TerminalDisplay will handle repainting its entire area. - setAttribute(Qt::WA_OpaquePaintEvent); - - _gridLayout = new QGridLayout(this); - _gridLayout->setContentsMargins(0, 0, 0, 0); - - setLayout( _gridLayout ); - - _charWidth = new CharWidth(font()); - - _isLocked = false; - _lockbackgroundImage = QPixmap(10,10); - _lockbackgroundImage.fill(Qt::gray); - - _backgroundVideoPlayer = new QMediaPlayer; - _backgroundVideoSink = new QVideoSink; - _backgroundVideoPlayer->setLoops(QMediaPlayer::Infinite); - _backgroundVideoPlayer->setVideoOutput(_backgroundVideoSink); - connect(_backgroundVideoSink, &QVideoSink::videoFrameChanged, this, [&](const QVideoFrame &frame){ - _backgroundVideoFrame = QPixmap::fromImage(frame.toImage()); - update(); - }); + : QWidget(parent), _screenWindow(nullptr), _allowBell(true), + _gridLayout(nullptr), _fontHeight(1), _fontWidth(1), _fontAscent(1), + _boldIntense(true), _lines(1), _columns(1), _usedLines(1), + _usedColumns(1), _contentHeight(1), _contentWidth(1), _image(nullptr), + _resizing(false), _terminalSizeHint(false), _terminalSizeStartup(true), + _bidiEnabled(true), _mouseMarks(false), _isPrimaryScreen(true), + _disabledBracketedPasteMode(false), _showResizeNotificationEnabled(true), + _actSel(0), _wordSelectionMode(false), _lineSelectionMode(false), + _preserveLineBreaks(false), _columnSelectionMode(false), + _scrollbarLocation(QTermWidget::NoScrollBar), + _wordCharacters(QLatin1String(":@-./_~")), _bellMode(SystemBeepBell), + _blinking(false), _hasBlinker(false), _cursorBlinking(false), + _hasBlinkingCursor(false), _allowBlinkingText(true), _ctrlDrag(false), + _tripleClickMode(SelectWholeLine), _isFixedSize(false), + _possibleTripleClick(false), _resizeWidget(nullptr), + _resizeTimer(nullptr), _flowControlWarningEnabled(false), + _outputSuspendedLabel(nullptr), _lineSpacing(0), _colorsInverted(false), + _opacity(static_cast(1)), _backgroundMode(None), + _selectedTextOpacity(static_cast(1)), + _filterChain(new TerminalImageFilterChain()), + _cursorShape(Emulation::KeyboardCursorShape::BlockCursor), + mMotionAfterPasting(NoMoveScreenWindow), _leftBaseMargin(1), + _topBaseMargin(1), _drawLineChars(true) { + // variables for draw text + _drawTextAdditionHeight = 0; + _drawTextTestFlag = false; + + // terminal applications are not designed with Right-To-Left in mind, + // so the layout is forced to Left-To-Right + setLayoutDirection(Qt::LeftToRight); + + // The offsets are not yet calculated. + // Do not calculate these too often to be more smoothly when resizing + // konsole in opaque mode. + _topMargin = _topBaseMargin; + _leftMargin = _leftBaseMargin; + + // create scroll bar for scrolling output up and down + // set the scroll bar's slider to occupy the whole area of the scroll bar + // initially + _scrollBar = new QScrollBar(this); + QString style_sheet = qApp->styleSheet(); + _scrollBar->setStyleSheet(style_sheet); + // since the contrast with the terminal background may not be enough, + // the scrollbar should be auto-filled if not transient + if (!_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + _scrollBar->setAutoFillBackground(true); + setScroll(0, 0); + _scrollBar->setCursor(Qt::ArrowCursor); + connect(_scrollBar, &QScrollBar::valueChanged, this, + &TerminalDisplay::scrollBarPositionChanged); + // qtermwidget: we have to hide it here due the + // _scrollbarLocation==NoScrollBar check in + // TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) + _scrollBar->hide(); + + // setup timers for blinking cursor and text + _blinkTimer = new QTimer(this); + connect(_blinkTimer, &QTimer::timeout, this, &TerminalDisplay::blinkEvent); + _blinkCursorTimer = new QTimer(this); + connect(_blinkCursorTimer, &QTimer::timeout, this, + &TerminalDisplay::blinkCursorEvent); + + // KCursor::setAutoHideCursor( this, true ); + + setUsesMouse(true); + setBracketedPasteMode(false); + setColorTable(base_color_table); + setMouseTracking(true); + + // Enable drag and drop + setAcceptDrops(true); // attempt + dragInfo.state = diNone; + + setFocusPolicy(Qt::WheelFocus); + + // enable input method support + setAttribute(Qt::WA_InputMethodEnabled, true); + setInputMethodHints(Qt::ImhSensitiveData | Qt::ImhNoAutoUppercase | + Qt::ImhNoPredictiveText | Qt::ImhMultiLine); + + // this is an important optimization, it tells Qt + // that TerminalDisplay will handle repainting its entire area. + setAttribute(Qt::WA_OpaquePaintEvent); + + _gridLayout = new QGridLayout(this); + _gridLayout->setContentsMargins(0, 0, 0, 0); + + setLayout(_gridLayout); - new AutoScrollHandler(this); + _charWidth = new CharWidth(font()); + + _isLocked = false; + _lockbackgroundImage = QPixmap(10, 10); + _lockbackgroundImage.fill(Qt::gray); + + _backgroundVideoPlayer = new QMediaPlayer; + _backgroundVideoSink = new QVideoSink; + _backgroundVideoPlayer->setLoops(QMediaPlayer::Infinite); + _backgroundVideoPlayer->setVideoOutput(_backgroundVideoSink); + connect(_backgroundVideoSink, &QVideoSink::videoFrameChanged, this, [&](const QVideoFrame &frame) { + _backgroundVideoFrame = QPixmap::fromImage(frame.toImage()); + update(); + }); + + new AutoScrollHandler(this); } -TerminalDisplay::~TerminalDisplay() -{ - if(_backgroundVideoPlayer->isPlaying()) { - _backgroundVideoPlayer->stop(); - } - delete _backgroundVideoPlayer; - delete _backgroundVideoSink; - if(_backgroundMovie != nullptr) { - _backgroundMovie->stop(); - QObject::disconnect(_backgroundMovie, nullptr, this, nullptr); - delete _backgroundMovie; - } - disconnect(_blinkTimer); - disconnect(_blinkCursorTimer); - qApp->removeEventFilter( this ); - - delete[] _image; - - delete _charWidth; - delete _gridLayout; - delete _outputSuspendedLabel; - delete _filterChain; +TerminalDisplay::~TerminalDisplay() { + if (_backgroundVideoPlayer->isPlaying()) { + _backgroundVideoPlayer->stop(); + } + delete _backgroundVideoPlayer; + delete _backgroundVideoSink; + if (_backgroundMovie != nullptr) { + _backgroundMovie->stop(); + QObject::disconnect(_backgroundMovie, nullptr, this, nullptr); + delete _backgroundMovie; + } + disconnect(_blinkTimer); + disconnect(_blinkCursorTimer); + qApp->removeEventFilter(this); + + delete[] _image; + + delete _charWidth; + delete _gridLayout; + delete _outputSuspendedLabel; + delete _filterChain; } /* ------------------------------------------------------------------------- */ @@ -478,8 +442,9 @@ TerminalDisplay::~TerminalDisplay() /** A table for emulating the simple (single width) unicode drawing chars. It represents the 250x - 257x glyphs. If it's zero, we can't use it. - if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered - 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit. + if it's not, it's encoded as follows: imagine a 5x5 grid where the points are + numbered 0 to 24 left to top, top to bottom. Each point is represented by the + corresponding bit. Then, the pixels basically have the following interpretation: _|||_ @@ -488,111 +453,130 @@ TerminalDisplay::~TerminalDisplay() -...- _|||_ -where _ = none + where _ = none | = vertical line. - = horizontal line. */ - -enum LineEncode -{ - TopL = (1<<1), - TopC = (1<<2), - TopR = (1<<3), - - LeftT = (1<<5), - Int11 = (1<<6), - Int12 = (1<<7), - Int13 = (1<<8), - RightT = (1<<9), - - LeftC = (1<<10), - Int21 = (1<<11), - Int22 = (1<<12), - Int23 = (1<<13), - RightC = (1<<14), - - LeftB = (1<<15), - Int31 = (1<<16), - Int32 = (1<<17), - Int33 = (1<<18), - RightB = (1<<19), - - BotL = (1<<21), - BotC = (1<<22), - BotR = (1<<23) +enum LineEncode { + TopL = (1 << 1), + TopC = (1 << 2), + TopR = (1 << 3), + + LeftT = (1 << 5), + Int11 = (1 << 6), + Int12 = (1 << 7), + Int13 = (1 << 8), + RightT = (1 << 9), + + LeftC = (1 << 10), + Int21 = (1 << 11), + Int22 = (1 << 12), + Int23 = (1 << 13), + RightC = (1 << 14), + + LeftB = (1 << 15), + Int31 = (1 << 16), + Int32 = (1 << 17), + Int33 = (1 << 18), + RightB = (1 << 19), + + BotL = (1 << 21), + BotC = (1 << 22), + BotR = (1 << 23) }; -#include "LineFont.h" +static const quint32 LineChars[] = { + 0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, 0x00421c00, 0x00439ce0, + 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, + 0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, + 0x004279ce, 0x00e77884, 0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, + 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, 0x00e73dce, 0x0047bdee, + 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, + 0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, + 0x000e7f84, 0x000fffe4, 0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, + 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, 0x00427dce, 0x00e77c84, + 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, + 0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, + 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, 0x000e1384, 0x0000794a, + 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, + 0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, + 0x00ad83e0, 0x000f83e4, 0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, + 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, + 0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, + 0x0003fce0, 0x004239ce +}; -static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uint8_t code) -{ - //Calculate cell midpoints, end points. - int cx = x + w/2; - int cy = y + h/2; +static void drawLineChar(QPainter &paint, int x, int y, int w, int h, uint8_t code) { + // Calculate cell midpoints, end points. + int cx = x + w / 2; + int cy = y + h / 2; int ex = x + w - 1; int ey = y + h - 1; quint32 toDraw = LineChars[code]; - //Top _lines: + // Top _lines: if (toDraw & TopL) - paint.drawLine(cx-1, y, cx-1, cy-2); + paint.drawLine(cx - 1, y, cx - 1, cy - 2); if (toDraw & TopC) - paint.drawLine(cx, y, cx, cy-2); + paint.drawLine(cx, y, cx, cy - 2); if (toDraw & TopR) - paint.drawLine(cx+1, y, cx+1, cy-2); + paint.drawLine(cx + 1, y, cx + 1, cy - 2); - //Bot _lines: + // Bot _lines: if (toDraw & BotL) - paint.drawLine(cx-1, cy+2, cx-1, ey); + paint.drawLine(cx - 1, cy + 2, cx - 1, ey); if (toDraw & BotC) - paint.drawLine(cx, cy+2, cx, ey); + paint.drawLine(cx, cy + 2, cx, ey); if (toDraw & BotR) - paint.drawLine(cx+1, cy+2, cx+1, ey); + paint.drawLine(cx + 1, cy + 2, cx + 1, ey); - //Left _lines: + // Left _lines: if (toDraw & LeftT) - paint.drawLine(x, cy-1, cx-2, cy-1); + paint.drawLine(x, cy - 1, cx - 2, cy - 1); if (toDraw & LeftC) - paint.drawLine(x, cy, cx-2, cy); + paint.drawLine(x, cy, cx - 2, cy); if (toDraw & LeftB) - paint.drawLine(x, cy+1, cx-2, cy+1); + paint.drawLine(x, cy + 1, cx - 2, cy + 1); - //Right _lines: + // Right _lines: if (toDraw & RightT) - paint.drawLine(cx+2, cy-1, ex, cy-1); + paint.drawLine(cx + 2, cy - 1, ex, cy - 1); if (toDraw & RightC) - paint.drawLine(cx+2, cy, ex, cy); + paint.drawLine(cx + 2, cy, ex, cy); if (toDraw & RightB) - paint.drawLine(cx+2, cy+1, ex, cy+1); + paint.drawLine(cx + 2, cy + 1, ex, cy + 1); - //Intersection points. + // Intersection points. if (toDraw & Int11) - paint.drawPoint(cx-1, cy-1); + paint.drawPoint(cx - 1, cy - 1); if (toDraw & Int12) - paint.drawPoint(cx, cy-1); + paint.drawPoint(cx, cy - 1); if (toDraw & Int13) - paint.drawPoint(cx+1, cy-1); + paint.drawPoint(cx + 1, cy - 1); if (toDraw & Int21) - paint.drawPoint(cx-1, cy); + paint.drawPoint(cx - 1, cy); if (toDraw & Int22) paint.drawPoint(cx, cy); if (toDraw & Int23) - paint.drawPoint(cx+1, cy); + paint.drawPoint(cx + 1, cy); if (toDraw & Int31) - paint.drawPoint(cx-1, cy+1); + paint.drawPoint(cx - 1, cy + 1); if (toDraw & Int32) - paint.drawPoint(cx, cy+1); + paint.drawPoint(cx, cy + 1); if (toDraw & Int33) - paint.drawPoint(cx+1, cy+1); + paint.drawPoint(cx + 1, cy + 1); } -static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar code) -{ - //Calculate cell midpoints, end points. +static void drawOtherChar(QPainter &paint, int x, int y, int w, int h, uchar code) { + // Calculate cell midpoints, end points. const int cx = x + w / 2; const int cy = y + h / 2; const int ex = x + w - 1; @@ -671,83 +655,77 @@ static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar cod } } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const std::wstring& str, - const Character* attributes) const -{ - const QPen& currentPen = painter.pen(); +void TerminalDisplay::drawLineCharString(QPainter &painter, int x, int y, + const std::wstring &str, + const Character *attributes) const { + const QPen ¤tPen = painter.pen(); - #if !defined(Q_OS_WIN) - if ( (attributes->rendition & RE_BOLD) && _boldIntense ) - { - QPen boldPen(currentPen); - boldPen.setWidth(3); - painter.setPen( boldPen ); - } - #endif +#if !defined(Q_OS_WIN) + if ((attributes->rendition & RE_BOLD) && _boldIntense) { + QPen boldPen(currentPen); + boldPen.setWidth(3); + painter.setPen(boldPen); + } +#endif - for (size_t i=0 ; i < str.length(); i++) - { - uint8_t code = static_cast(str[i] & 0xffU); - if (LineChars[code]) - drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); - else - drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code); - } + for (size_t i = 0; i < str.length(); i++) { + uint8_t code = static_cast(str[i] & 0xffU); + if (LineChars[code]) + drawLineChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, + code); + else + drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, + code); + } - painter.setPen( currentPen ); + painter.setPen(currentPen); } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, wchar_t ch, - const Character* attributes) const -{ - const QPen& currentPen = painter.pen(); +void TerminalDisplay::drawLineCharString(QPainter &painter, int x, int y, + wchar_t ch, + const Character *attributes) const { + const QPen ¤tPen = painter.pen(); - #if !defined(Q_OS_WIN) - if ( (attributes->rendition & RE_BOLD) && _boldIntense ) - { - QPen boldPen(currentPen); - boldPen.setWidth(3); - painter.setPen( boldPen ); - } - #endif +#if !defined(Q_OS_WIN) + if ((attributes->rendition & RE_BOLD) && _boldIntense) { + QPen boldPen(currentPen); + boldPen.setWidth(3); + painter.setPen(boldPen); + } +#endif - uint8_t code = static_cast(ch & 0xffU); - if (LineChars[code]) - drawLineChar(painter, x, y, _fontWidth, _fontHeight, code); - else - drawOtherChar(painter, x, y, _fontWidth, _fontHeight, code); + uint8_t code = static_cast(ch & 0xffU); + if (LineChars[code]) + drawLineChar(painter, x, y, _fontWidth, _fontHeight, code); + else + drawOtherChar(painter, x, y, _fontWidth, _fontHeight, code); - painter.setPen( currentPen ); + painter.setPen(currentPen); } -void TerminalDisplay::setKeyboardCursorShape(QTermWidget::KeyboardCursorShape shape) -{ +void TerminalDisplay::setKeyboardCursorShape( + QTermWidget::KeyboardCursorShape shape) { _cursorShape = shape; updateCursor(); } -QTermWidget::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const -{ +QTermWidget::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const { return _cursorShape; } -void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color) -{ +void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, + const QColor &color) { if (useForegroundColor) _cursorColor = QColor(); // an invalid color means that - // the foreground color of the - // current character should - // be used + // the foreground color of the + // current character should + // be used else _cursorColor = color; } -QColor TerminalDisplay::keyboardCursorColor() const -{ - return _cursorColor; -} +QColor TerminalDisplay::keyboardCursorColor() const { return _cursorColor; } -void TerminalDisplay::setOpacity(qreal opacity) -{ +void TerminalDisplay::setOpacity(qreal opacity) { _opacity = qBound(static_cast(0), opacity, static_cast(1)); } @@ -762,9 +740,7 @@ void TerminalDisplay::setBackgroundPixmap(QPixmap *backgroundImage) { } } -void TerminalDisplay::reloadBackgroundPixmap(void) { - update(); -} +void TerminalDisplay::reloadBackgroundPixmap(void) { update(); } void TerminalDisplay::setBackgroundImage(const QString &backgroundImage) { if (!backgroundImage.isEmpty()) { @@ -824,25 +800,24 @@ void TerminalDisplay::setBackgroundVideo(const QString &backgroundVideo) { } } -void TerminalDisplay::setBackgroundMode(BackgroundMode mode) -{ +void TerminalDisplay::setBackgroundMode(BackgroundMode mode) { _backgroundMode = mode; } -void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting ) -{ +void TerminalDisplay::drawBackground(QPainter &painter, const QRect &rect, + const QColor &backgroundColor, + bool useOpacitySetting) { QPixmap currentBackgroundImage = _backgroundImage; - if(_backgroundMovie != nullptr) { + if (_backgroundMovie != nullptr) { currentBackgroundImage = _backgroundMovie->currentPixmap(); } - if(_backgroundVideoPlayer->isPlaying()) { + if (_backgroundVideoPlayer->isPlaying()) { currentBackgroundImage = _backgroundVideoFrame; } // The whole widget rectangle is filled by the background color from // the color scheme set in setColorTable(), while the scrollbar is // left to the widget style for a consistent look. - if ( useOpacitySetting ) - { + if (useOpacitySetting) { QColor color(backgroundColor); if (currentBackgroundImage.isNull()) { color.setAlphaF(1.0); @@ -853,247 +828,252 @@ void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.fillRect(rect, color); painter.restore(); - } - else + } else painter.fillRect(rect, backgroundColor); } -void TerminalDisplay::drawCursor(QPainter& painter, - const QRect& rect, - const QColor& foregroundColor, - const QColor& /*backgroundColor*/, - bool& invertCharacterColor, - bool preedit) -{ +void TerminalDisplay::drawCursor(QPainter &painter, const QRect &rect, + const QColor &foregroundColor, + const QColor & /*backgroundColor*/, + bool &invertCharacterColor, bool preedit) { QRectF cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); - if (!_cursorBlinking) - { - if ( _cursorColor.isValid() ) - painter.setPen(_cursorColor); - else - painter.setPen(foregroundColor); + if (!_cursorBlinking) { + if (_cursorColor.isValid()) + painter.setPen(_cursorColor); + else + painter.setPen(foregroundColor); - if ( _cursorShape == Emulation::KeyboardCursorShape::BlockCursor ) - { + if (_cursorShape == Emulation::KeyboardCursorShape::BlockCursor) { // draw the cursor outline, adjusting the area so that // it is draw entirely inside 'rect' - float penWidth = qMax(1,painter.pen().width()); + float penWidth = qMax(1, painter.pen().width()); - if(preedit) { - // with is single character, so the cursor width should be the same as the character width - cursorRect.setWidth( _fontWidth ); + if (preedit) { + // with is single character, so the cursor width should be the same as + // the character width + cursorRect.setWidth(_fontWidth); } - painter.drawRect(cursorRect.adjusted(penWidth/2, - penWidth/2, - - penWidth/2, - - penWidth/2)); + painter.drawRect(cursorRect.adjusted(penWidth / 2, penWidth / 2, -penWidth / 2, -penWidth / 2)); - if ( preedit || hasFocus() ) { - painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor); - if ( !_cursorColor.isValid() ) { - // invert the colour used to draw the text to ensure that the character at - // the cursor position is readable + if (preedit || hasFocus()) { + painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor + : foregroundColor); + if (!_cursorColor.isValid()) { + // invert the colour used to draw the text to ensure that the + // character at the cursor position is readable invertCharacterColor = true; } } - } - else if ( _cursorShape == Emulation::KeyboardCursorShape::UnderlineCursor ) - painter.drawLine(cursorRect.left(), - cursorRect.bottom(), - cursorRect.right(), - cursorRect.bottom()); - else if ( _cursorShape == Emulation::KeyboardCursorShape::IBeamCursor ) - painter.drawLine(cursorRect.left(), - cursorRect.top(), - cursorRect.left(), - cursorRect.bottom()); - } -} - -void TerminalDisplay::drawCharacters(QPainter& painter, - const QRect& rect, - const std::wstring& text, - const Character* style, - bool invertCharacterColor) -{ + } else if (_cursorShape == Emulation::KeyboardCursorShape::UnderlineCursor) + painter.drawLine(cursorRect.left(), cursorRect.bottom(), + cursorRect.right(), cursorRect.bottom()); + else if (_cursorShape == Emulation::KeyboardCursorShape::IBeamCursor) + painter.drawLine(cursorRect.left(), cursorRect.top(), cursorRect.left(), + cursorRect.bottom()); + } +} + +void TerminalDisplay::drawCharacters(QPainter &painter, const QRect &rect, + const std::wstring &text, + const Character *style, + bool invertCharacterColor) { // don't draw text which is currently blinking - if ( _blinking && (style->rendition & RE_BLINK) ) + if (_blinking && (style->rendition & RE_BLINK)) return; // don't draw concealed characters if (style->rendition & RE_CONCEAL) - return; + return; // setup bold and underline - bool useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); - const bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); + bool useBold = + ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); + const bool useUnderline = + style->rendition & RE_UNDERLINE || font().underline(); const bool useItalic = style->rendition & RE_ITALIC || font().italic(); - const bool useStrikeOut = style->rendition & RE_STRIKEOUT || font().strikeOut(); + const bool useStrikeOut = + style->rendition & RE_STRIKEOUT || font().strikeOut(); const bool useOverline = style->rendition & RE_OVERLINE || font().overline(); QFont font = painter.font(); - if ( font.bold() != useBold - || font.underline() != useUnderline - || font.italic() != useItalic - || font.strikeOut() != useStrikeOut - || font.overline() != useOverline) { - #if !defined(Q_OS_WIN) - font.setBold(useBold); - #endif - font.setUnderline(useUnderline); - font.setItalic(useItalic); - font.setStrikeOut(useStrikeOut); - font.setOverline(useOverline); - painter.setFont(font); + if (font.bold() != useBold || font.underline() != useUnderline || + font.italic() != useItalic || font.strikeOut() != useStrikeOut || + font.overline() != useOverline) { +#if !defined(Q_OS_WIN) + font.setBold(useBold); +#endif + font.setUnderline(useUnderline); + font.setItalic(useItalic); + font.setStrikeOut(useStrikeOut); + font.setOverline(useOverline); + painter.setFont(font); } // setup pen - const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); + const CharacterColor &textColor = + (invertCharacterColor ? style->backgroundColor : style->foregroundColor); const QColor color = textColor.color(_colorTable); QPen pen = painter.pen(); - if ( pen.color() != color ) - { + if (pen.color() != color) { pen.setColor(color); painter.setPen(color); } - // FIXME: Here is a hack to solve the East Asian language symbol "“‘" rendering issue. - // But it is not a good solution. We should find a better way to solve this issue. + // FIXME: Here is a hack to solve the East Asian language symbol + // "“‘" rendering issue. + // But it is not a good solution. We should find a better way to solve + // this issue. int font_width = _charWidth->string_font_width(text); int width = CharWidth::string_unicode_width(text); - if(_fix_quardCRT_issue33 && font_width != width) { - int single_rect_width = rect.width() / width; - for (size_t i=0 ; i < text.length(); i++) { - wchar_t line_char = text[i]; - if ( isLineChar(line_char) ) { - drawLineCharString(painter, rect.x() + single_rect_width * i, rect.y(), line_char, style); - } else { - if(_charWidth->font_width(line_char) != CharWidth::unicode_width(line_char)) { - // https://github.com/QQxiaoming/quardCRT/issues/33#issuecomment-2044020900 - // | left | center | right | - // | ------------ | ------------ | ------------ | - // | L'’' U+2019 | L'×' U+00D7 | L'‘' U+2018 | - // | L'”' U+201D | L'÷' U+00F7 | L'“' U+201C | - // | | L'‖' U+2016 | L'‚' U+201A | - // | | | L'‛' U+201B | - const QList right_chars = - {0x201C, 0x2018, 0x201A, 0x201B }; - const QList center_chars = - {0x00D7, 0x00F7, 0x2016}; - const QList left_chars = - {0x201D, 0x2019, 0x2580, 0x2584, 0x2588}; - if(right_chars.contains(line_char)) { - int offset = single_rect_width*(_charWidth->font_width(line_char)-CharWidth::unicode_width(line_char)); - painter.save(); - QRect rightHalfRect(rect.x() + single_rect_width * i, rect.y(), single_rect_width, _fontHeight); - painter.setClipRect(rightHalfRect); - painter.drawText(rect.x() + single_rect_width * i - offset, rect.y() + _fontAscent + _lineSpacing, QString::fromWCharArray(&line_char,1)); - painter.restore(); - } else if(center_chars.contains(line_char)) { - int offset = single_rect_width*(_charWidth->font_width(line_char)-CharWidth::unicode_width(line_char))/2; - painter.save(); - QRect rightHalfRect(rect.x() + single_rect_width * i, rect.y(), single_rect_width, _fontHeight); - painter.setClipRect(rightHalfRect); - painter.drawText(rect.x() + single_rect_width * i - offset, rect.y() + _fontAscent + _lineSpacing, QString::fromWCharArray(&line_char,1)); - painter.restore(); - } else if(left_chars.contains(line_char)) { - QRect rectangle(rect.x() + single_rect_width * i, rect.y(), single_rect_width, _fontHeight); - painter.drawText(rectangle, 0, QString::fromWCharArray(&line_char,1)); - } else { - painter.drawText(rect.x() + single_rect_width * i, rect.y() + _fontAscent + _lineSpacing, QString::fromWCharArray(&line_char,1)); - } + if (_fix_quardCRT_issue33 && font_width != width) { + int single_rect_width = rect.width() / width; + for (size_t i = 0; i < text.length(); i++) { + wchar_t line_char = text[i]; + if (isLineChar(line_char)) { + drawLineCharString(painter, rect.x() + single_rect_width * i, rect.y(), + line_char, style); } else { - painter.drawText(rect.x() + single_rect_width * i, rect.y() + _fontAscent + _lineSpacing, QString::fromWCharArray(&line_char,1)); + if (_charWidth->font_width(line_char) != + CharWidth::unicode_width(line_char)) { + // https://github.com/QQxiaoming/quardCRT/issues/33#issuecomment-2044020900 + // | left | center | right | + // | ------------ | ------------ | ------------ | + // | L'’' U+2019 | L'×' U+00D7 | L'‘' U+2018 | + // | L'”' U+201D | L'÷' U+00F7 | L'“' U+201C | + // | | L'‖' U+2016 | L'‚' U+201A | + // | | | L'‛' U+201B | + const QList right_chars = {0x201C, 0x2018, 0x201A, 0x201B}; + const QList center_chars = {0x00D7, 0x00F7, 0x2016}; + const QList left_chars = {0x201D, 0x2019, 0x2580, 0x2584, 0x2588}; + if (right_chars.contains(line_char)) { + int offset = + single_rect_width * (_charWidth->font_width(line_char) - + CharWidth::unicode_width(line_char)); + painter.save(); + QRect rightHalfRect(rect.x() + single_rect_width * i, rect.y(), + single_rect_width, _fontHeight); + painter.setClipRect(rightHalfRect); + painter.drawText(rect.x() + single_rect_width * i - offset, + rect.y() + _fontAscent + _lineSpacing, + QString::fromWCharArray(&line_char, 1)); + painter.restore(); + } else if (center_chars.contains(line_char)) { + int offset = single_rect_width * + (_charWidth->font_width(line_char) - + CharWidth::unicode_width(line_char)) / + 2; + painter.save(); + QRect rightHalfRect(rect.x() + single_rect_width * i, rect.y(), + single_rect_width, _fontHeight); + painter.setClipRect(rightHalfRect); + painter.drawText(rect.x() + single_rect_width * i - offset, + rect.y() + _fontAscent + _lineSpacing, + QString::fromWCharArray(&line_char, 1)); + painter.restore(); + } else if (left_chars.contains(line_char)) { + QRect rectangle(rect.x() + single_rect_width * i, rect.y(), + single_rect_width, _fontHeight); + painter.drawText(rectangle, 0, + QString::fromWCharArray(&line_char, 1)); + } else { + painter.drawText(rect.x() + single_rect_width * i, + rect.y() + _fontAscent + _lineSpacing, + QString::fromWCharArray(&line_char, 1)); + } + } else { + painter.drawText(rect.x() + single_rect_width * i, + rect.y() + _fontAscent + _lineSpacing, + QString::fromWCharArray(&line_char, 1)); + } } - } } } else { - // draw text - if ( isLineCharString(text) ) { - drawLineCharString(painter,rect.x(),rect.y(),text,style); - } else { - // Force using LTR as the document layout for the terminal area, because - // there is no use cases for RTL emulator and RTL terminal application. - // - // This still allows RTL characters to be rendered in the RTL way. - painter.setLayoutDirection(Qt::LeftToRight); - - if (_bidiEnabled) { - painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, QString::fromStdWString(text)); + // draw text + if (isLineCharString(text)) { + drawLineCharString(painter, rect.x(), rect.y(), text, style); } else { - QRect drawRect(rect.topLeft(), rect.size()); - drawRect.setHeight(rect.height() + _drawTextAdditionHeight); - painter.drawText(drawRect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QString::fromStdWString(text)); + // Force using LTR as the document layout for the terminal area, because + // there is no use cases for RTL emulator and RTL terminal application. + // + // This still allows RTL characters to be rendered in the RTL way. + painter.setLayoutDirection(Qt::LeftToRight); + + if (_bidiEnabled) { + painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, + QString::fromStdWString(text)); + } else { + QRect drawRect(rect.topLeft(), rect.size()); + drawRect.setHeight(rect.height() + _drawTextAdditionHeight); + painter.drawText(drawRect, Qt::AlignBottom, + LTR_OVERRIDE_CHAR + QString::fromStdWString(text)); + } } - } } } -void TerminalDisplay::drawTextFragment(QPainter& painter , - const QRect& rect, - const std::wstring& text, - Character* style, - bool isSelection) -{ +void TerminalDisplay::drawTextFragment(QPainter &painter, const QRect &rect, + const std::wstring &text, + Character *style, bool isSelection) { painter.save(); - // when the selected text is not opaque, the text is drawn with inverted colors - // but else the text is drawn with the normal colors - if(_selectedTextOpacity < 1.0) { - if (isSelection) { - CharacterColor f = style->foregroundColor; - CharacterColor b = style->backgroundColor; - style->foregroundColor = b; - style->backgroundColor = f; - } + // when the selected text is not opaque, the text is drawn with inverted + // colors but else the text is drawn with the normal colors + if (_selectedTextOpacity < 1.0) { + if (isSelection) { + CharacterColor f = style->foregroundColor; + CharacterColor b = style->backgroundColor; + style->foregroundColor = b; + style->backgroundColor = f; + } } // setup painter const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); - + // draw background if different from the display's background color - if ( backgroundColor != _colorTable[DEFAULT_BACK_COLOR].color ) { - drawBackground(painter,rect,backgroundColor, - false /* do not use transparency */); + if (backgroundColor != _colorTable[DEFAULT_BACK_COLOR].color) { + drawBackground(painter, rect, backgroundColor, + false /* do not use transparency */); } // draw cursor shape if the current character is the cursor // this may alter the foreground and background colors bool invertCharacterColor = false; - if ( style->rendition & RE_CURSOR ) - drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor); + if (style->rendition & RE_CURSOR) + drawCursor(painter, rect, foregroundColor, backgroundColor, + invertCharacterColor); // draw text - drawCharacters(painter,rect,text,style,invertCharacterColor); + drawCharacters(painter, rect, text, style, invertCharacterColor); painter.restore(); - if(_selectedTextOpacity < 1.0) { - if (isSelection) { - painter.save(); - painter.setOpacity(_selectedTextOpacity); - painter.setRenderHint(QPainter::SmoothPixmapTransform, false); - painter.setRenderHint(QPainter::Antialiasing, false); - painter.fillRect(rect, CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR).color(_colorTable)); - painter.restore(); - CharacterColor f = style->foregroundColor; - CharacterColor b = style->backgroundColor; - style->foregroundColor = b; - style->backgroundColor = f; - } + if (_selectedTextOpacity < 1.0) { + if (isSelection) { + painter.save(); + painter.setOpacity(_selectedTextOpacity); + painter.setRenderHint(QPainter::SmoothPixmapTransform, false); + painter.setRenderHint(QPainter::Antialiasing, false); + painter.fillRect(rect, CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR) + .color(_colorTable)); + painter.restore(); + CharacterColor f = style->foregroundColor; + CharacterColor b = style->backgroundColor; + style->foregroundColor = b; + style->backgroundColor = f; + } } } #if 0 /*! - Set XIM Position + Set XIM Position */ -void TerminalDisplay::setCursorPos(const int curx, const int cury) -{ +void TerminalDisplay::setCursorPos(const int curx, const int cury) { QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); @@ -1111,17 +1091,16 @@ void TerminalDisplay::setCursorPos(const int curx, const int cury) // scrolls the image by 'lines', down if lines > 0 or up otherwise. // // the terminal emulation keeps track of the scrolling of the character -// image as it receives input, and when the view is updated, it calls scrollImage() -// with the final scroll amount. this improves performance because scrolling the -// display is much cheaper than re-rendering all the text for the -// part of the image which has moved up or down. -// Instead only new lines have to be drawn -void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) -{ +// image as it receives input, and when the view is updated, it calls +// scrollImage() with the final scroll amount. this improves performance +// because scrolling the display is much cheaper than re-rendering all the text +// for the part of the image which has moved up or down. Instead only new lines +// have to be drawn +void TerminalDisplay::scrollImage(int lines, const QRect &screenWindowRegion) { // if the flow control warning is enabled this will interfere with the // scrolling optimizations and cause artifacts. the simple solution here // is to just disable the optimization whilst it is visible - if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) + if (_outputSuspendedLabel && _outputSuspendedLabel->isVisible()) return; // constrain the region to the display @@ -1129,14 +1108,13 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; - region.setBottom( qMin(region.bottom(),this->_lines-2) ); + region.setBottom(qMin(region.bottom(), this->_lines - 2)); // return if there is nothing to do - if ( lines == 0 - || _image == nullptr - || !region.isValid() - || (region.top() + abs(lines)) >= region.bottom() - || this->_lines <= region.height() ) return; + if (lines == 0 || _image == nullptr || !region.isValid() || + (region.top() + abs(lines)) >= region.bottom() || + this->_lines <= region.height()) + return; // hide terminal size label to prevent it being scrolled if (_resizeWidget && _resizeWidget->isVisible()) @@ -1152,106 +1130,102 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // Set the QT_FLUSH_PAINT environment variable to '1' before starting the // application to monitor repainting. // - int scrollBarWidth = _scrollBar->isHidden() ? 0 : - _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) ? - 0 : _scrollBar->width(); + int scrollBarWidth = + _scrollBar->isHidden() ? 0 + : _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) + ? 0 + : _scrollBar->width(); const int SCROLLBAR_CONTENT_GAP = scrollBarWidth == 0 ? 0 : 1; QRect scrollRect; - if ( _scrollbarLocation == QTermWidget::ScrollBarLeft ) - { - scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP); + if (_scrollbarLocation == QTermWidget::ScrollBarLeft) { + scrollRect.setLeft(scrollBarWidth + SCROLLBAR_CONTENT_GAP); scrollRect.setRight(width()); - } - else - { + } else { scrollRect.setLeft(0); scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); } - void* firstCharPos = &_image[ region.top() * this->_columns ]; - void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; + void *firstCharPos = &_image[region.top() * this->_columns]; + void *lastCharPos = &_image[(region.top() + abs(lines)) * this->_columns]; int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); - int bytesToMove = linesToMove * - this->_columns * - sizeof(Character); + int bytesToMove = linesToMove * this->_columns * sizeof(Character); - Q_ASSERT( linesToMove > 0 ); - Q_ASSERT( bytesToMove > 0 ); + Q_ASSERT(linesToMove > 0); + Q_ASSERT(bytesToMove > 0); - //scroll internal image - if ( lines > 0 ) - { + // scroll internal image + if (lines > 0) { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)lastCharPos + bytesToMove < - (char*)(_image + (this->_lines * this->_columns)) ); + Q_ASSERT((char *)lastCharPos + bytesToMove < + (char *)(_image + (this->_lines * this->_columns))); - Q_ASSERT( (lines*this->_columns) < _imageSize ); + Q_ASSERT((lines * this->_columns) < _imageSize); - //scroll internal image down - memmove( firstCharPos , lastCharPos , bytesToMove ); + // scroll internal image down + memmove(firstCharPos, lastCharPos, bytesToMove); - //set region of display to scroll + // set region of display to scroll scrollRect.setTop(top); - } - else - { + } else { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)firstCharPos + bytesToMove < - (char*)(_image + (this->_lines * this->_columns)) ); + Q_ASSERT((char *)firstCharPos + bytesToMove < + (char *)(_image + (this->_lines * this->_columns))); - //scroll internal image up - memmove( lastCharPos , firstCharPos , bytesToMove ); + // scroll internal image up + memmove(lastCharPos, firstCharPos, bytesToMove); - //set region of the display to scroll + // set region of the display to scroll scrollRect.setTop(top + abs(lines) * _fontHeight); } - scrollRect.setHeight(linesToMove * _fontHeight ); + scrollRect.setHeight(linesToMove * _fontHeight); Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty()); - //scroll the display vertically to match internal _image - scroll( 0 , _fontHeight * (-lines) , scrollRect ); + // scroll the display vertically to match internal _image + scroll(0, _fontHeight * (-lines), scrollRect); } -QRegion TerminalDisplay::hotSpotRegion() const -{ +QRegion TerminalDisplay::hotSpotRegion() const { QRegion region; const auto hotSpots = _filterChain->hotSpots(); - for( Filter::HotSpot* const hotSpot : hotSpots ) - { + for (Filter::HotSpot *const hotSpot : hotSpots) { QRect r; - if (hotSpot->startLine()==hotSpot->endLine()) { + if (hotSpot->startLine() == hotSpot->endLine()) { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); - region |= imageToWidget(r);; + region |= imageToWidget(r); + ; } else { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(_columns); r.setBottom(hotSpot->startLine()); - region |= imageToWidget(r);; - for ( int line = hotSpot->startLine()+1 ; line < hotSpot->endLine() ; line++ ) { + region |= imageToWidget(r); + ; + for (int line = hotSpot->startLine() + 1; line < hotSpot->endLine(); + line++) { r.setLeft(0); r.setTop(line); r.setRight(_columns); r.setBottom(line); - region |= imageToWidget(r);; + region |= imageToWidget(r); + ; } r.setLeft(0); r.setTop(hotSpot->endLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); - region |= imageToWidget(r);; + region |= imageToWidget(r); + ; } } return region; } -void TerminalDisplay::processFilters() -{ +void TerminalDisplay::processFilters() { if (!_screenWindow) return; @@ -1262,266 +1236,256 @@ void TerminalDisplay::processFilters() // ScreenWindow emits a scrolled() signal - which will happen before // updateImage() is called on the display and therefore _image is // out of date at this point - _filterChain->setImage( _screenWindow->getImage(), - _screenWindow->windowLines(), - _screenWindow->windowColumns(), - _screenWindow->getLineProperties() ); + _filterChain->setImage( + _screenWindow->getImage(), _screenWindow->windowLines(), + _screenWindow->windowColumns(), _screenWindow->getLineProperties()); _filterChain->process(); QRegion postUpdateHotSpots = hotSpotRegion(); - update( preUpdateHotSpots | postUpdateHotSpots ); + update(preUpdateHotSpots | postUpdateHotSpots); } -void TerminalDisplay::updateImage() -{ - if ( !_screenWindow ) - return; +void TerminalDisplay::updateImage() { + if (!_screenWindow) + return; - // optimization - scroll the existing image where possible and - // avoid expensive text drawing for parts of the image that - // can simply be moved up or down - scrollImage( _screenWindow->scrollCount() , - _screenWindow->scrollRegion() ); - _screenWindow->resetScrollCount(); + // optimization - scroll the existing image where possible and + // avoid expensive text drawing for parts of the image that + // can simply be moved up or down + scrollImage(_screenWindow->scrollCount(), _screenWindow->scrollRegion()); + _screenWindow->resetScrollCount(); - if (!_image) { - // Create _image. - // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first. - updateImageSize(); - } + if (!_image) { + // Create _image. + // The emitted changedContentSizeSignal also leads to getImage being + // recreated, so do this first. + updateImageSize(); + } - Character* const newimg = _screenWindow->getImage(); - int lines = _screenWindow->windowLines(); - int columns = _screenWindow->windowColumns(); + Character *const newimg = _screenWindow->getImage(); + int lines = _screenWindow->windowLines(); + int columns = _screenWindow->windowColumns(); - setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); + setScroll(_screenWindow->currentLine(), _screenWindow->lineCount()); - Q_ASSERT( this->_usedLines <= this->_lines ); - Q_ASSERT( this->_usedColumns <= this->_columns ); + Q_ASSERT(this->_usedLines <= this->_lines); + Q_ASSERT(this->_usedColumns <= this->_columns); - int y,x,len; + int y, x, len; - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); - _hasBlinker = false; + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + _hasBlinker = false; - CharacterColor cf; // undefined - CharacterColor _clipboard; // undefined - int cr = -1; // undefined + CharacterColor cf; // undefined + CharacterColor _clipboard; // undefined + int cr = -1; // undefined - const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); - const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); + const int linesToUpdate = qMin(this->_lines, qMax(0, lines)); + const int columnsToUpdate = qMin(this->_columns, qMax(0, columns)); - wchar_t *disstrU = new wchar_t[columnsToUpdate]; - char *dirtyMask = new char[columnsToUpdate+2]; - QRegion dirtyRegion; + wchar_t *disstrU = new wchar_t[columnsToUpdate]; + char *dirtyMask = new char[columnsToUpdate + 2]; + QRegion dirtyRegion; - // debugging variable, this records the number of lines that are found to - // be 'dirty' ( ie. have changed from the old _image to the new _image ) and - // which therefore need to be repainted - for (y = 0; y < linesToUpdate; ++y) - { - const Character* currentLine = &_image[y*this->_columns]; - const Character* const newLine = &newimg[y*columns]; + // debugging variable, this records the number of lines that are found to + // be 'dirty' ( ie. have changed from the old _image to the new _image ) and + // which therefore need to be repainted + for (y = 0; y < linesToUpdate; ++y) { + const Character *currentLine = &_image[y * this->_columns]; + const Character *const newLine = &newimg[y * columns]; - bool updateLine = false; + bool updateLine = false; - // The dirty mask indicates which characters need repainting. We also - // mark surrounding neighbours dirty, in case the character exceeds - // its cell boundaries - memset(dirtyMask, 0, columnsToUpdate+2); + // The dirty mask indicates which characters need repainting. We also + // mark surrounding neighbours dirty, in case the character exceeds + // its cell boundaries + memset(dirtyMask, 0, columnsToUpdate + 2); - for( x = 0 ; x < columnsToUpdate ; ++x) - { - if ( newLine[x] != currentLine[x] ) - { - dirtyMask[x] = true; + for (x = 0; x < columnsToUpdate; ++x) { + if (newLine[x] != currentLine[x]) { + dirtyMask[x] = true; + } } - } - if (!_resizing) // not while _resizing, we're expecting a paintEvent - for (x = 0; x < columnsToUpdate; ++x) - { - if ((newLine[x].rendition & RE_BLINK) != 0) { - _hasBlinker = true; - } - - // Start drawing if this character or the next one differs. - // We also take the next one into account to handle the situation - // where characters exceed their cell width. - if (dirtyMask[x]) - { - wchar_t c = newLine[x+0].character; - if ( !c ) - continue; - int p = 0; - disstrU[p++] = c; //fontMap(c); - bool lineDraw = isLineChar(c); - bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); - cr = newLine[x].rendition; - _clipboard = newLine[x].backgroundColor; - if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; - int lln = columnsToUpdate - x; - for (len = 1; len < lln; ++len) - { - const Character& ch = newLine[x+len]; + if (!_resizing) // not while _resizing, we're expecting a paintEvent + for (x = 0; x < columnsToUpdate; ++x) { + if ((newLine[x].rendition & RE_BLINK) != 0) { + _hasBlinker = true; + } - if (!ch.character) - continue; // Skip trailing part of multi-col chars. + // Start drawing if this character or the next one differs. + // We also take the next one into account to handle the situation + // where characters exceed their cell width. + if (dirtyMask[x]) { + wchar_t c = newLine[x + 0].character; + if (!c) + continue; + int p = 0; + disstrU[p++] = c; // fontMap(c); + bool lineDraw = isLineChar(c); + bool doubleWidth = (x + 1 == columnsToUpdate) + ? false + : (newLine[x + 1].character == 0); + cr = newLine[x].rendition; + _clipboard = newLine[x].backgroundColor; + if (newLine[x].foregroundColor != cf) + cf = newLine[x].foregroundColor; + int lln = columnsToUpdate - x; + for (len = 1; len < lln; ++len) { + const Character &ch = newLine[x + len]; + + if (!ch.character) + continue; // Skip trailing part of multi-col chars. + + bool nextIsDoubleWidth = + (x + len + 1 == columnsToUpdate) + ? false + : (newLine[x + len + 1].character == 0); + + if (ch.foregroundColor != cf || ch.backgroundColor != _clipboard || + ch.rendition != cr || !dirtyMask[x + len] || + isLineChar(c) != lineDraw || nextIsDoubleWidth != doubleWidth) + break; + + disstrU[p++] = c; // fontMap(c); + } + + std::wstring unistr(disstrU, p); + + bool saveFixedFont = _fixedFont; + if (lineDraw) + _fixedFont = false; + if (doubleWidth) + _fixedFont = false; + + updateLine = true; + + _fixedFont = saveFixedFont; + x += len - 1; + } + } - bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); + // both the top and bottom halves of double height _lines must always be + // redrawn although both top and bottom halves contain the same characters, + // only the top one is actually drawn. + if (_lineProperties.count() > y) { + if ((_lineProperties[y] & LINE_DOUBLEHEIGHT) != 0) { + updateLine = true; + } + } - if ( ch.foregroundColor != cf || - ch.backgroundColor != _clipboard || - ch.rendition != cr || - !dirtyMask[x+len] || - isLineChar(c) != lineDraw || - nextIsDoubleWidth != doubleWidth ) - break; + // if the characters on the line are different in the old and the new _image + // then this line must be repainted. + if (updateLine) { + // add the area occupied by this line to the region which needs to be + // repainted + QRect dirtyRect = + QRect(_leftMargin + tLx, _topMargin + tLy + _fontHeight * y, + _fontWidth * columnsToUpdate, _fontHeight); - disstrU[p++] = c; //fontMap(c); + dirtyRegion |= dirtyRect; } - std::wstring unistr(disstrU, p); + // replace the line of characters in the old _image with the + // current line of the new _image + memcpy((void *)currentLine, (const void *)newLine, + columnsToUpdate * sizeof(Character)); + } + + // if the new _image is smaller than the previous _image, then ensure that the + // area outside the new _image is cleared + if (linesToUpdate < _usedLines) { + dirtyRegion |= + QRect(_leftMargin + tLx, _topMargin + tLy + _fontHeight * linesToUpdate, + _fontWidth * this->_columns, + _fontHeight * (_usedLines - linesToUpdate)); + } + _usedLines = linesToUpdate; + + if (columnsToUpdate < _usedColumns) { + dirtyRegion |= + QRect(_leftMargin + tLx + columnsToUpdate * _fontWidth, + _topMargin + tLy, _fontWidth * (_usedColumns - columnsToUpdate), + _fontHeight * this->_lines); + } + _usedColumns = columnsToUpdate; - bool saveFixedFont = _fixedFont; - if (lineDraw) - _fixedFont = false; - if (doubleWidth) - _fixedFont = false; + dirtyRegion |= _inputMethodData.previousPreeditRect; - updateLine = true; + // update the parts of the display which have changed + update(dirtyRegion); - _fixedFont = saveFixedFont; - x += len - 1; - } + if (_hasBlinker && !_blinkTimer->isActive()) + _blinkTimer->start(TEXT_BLINK_DELAY); + if (!_hasBlinker && _blinkTimer->isActive()) { + _blinkTimer->stop(); + _blinking = false; } + delete[] dirtyMask; + delete[] disstrU; +} - //both the top and bottom halves of double height _lines must always be redrawn - //although both top and bottom halves contain the same characters, only - //the top one is actually - //drawn. - if (_lineProperties.count() > y) { - if ((_lineProperties[y] & LINE_DOUBLEHEIGHT) != 0) { - updateLine = true; +void TerminalDisplay::showResizeNotification() { + if (_terminalSizeHint && isVisible()) { + if (_terminalSizeStartup) { + _terminalSizeStartup = false; + return; + } + if (!_resizeWidget) { + const QString label = tr("Size: XXX x XXX"); + _resizeWidget = new QLabel(label, this); + _resizeWidget->setMinimumWidth( + _resizeWidget->fontMetrics().horizontalAdvance(label)); + _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); + _resizeWidget->setAlignment(Qt::AlignCenter); + + _resizeWidget->setStyleSheet(QLatin1String( + "background-color:palette(window);border-style:solid;border-width:" + "1px;border-color:palette(dark);color:palette(windowText);")); + + _resizeTimer = new QTimer(this); + _resizeTimer->setSingleShot(true); + connect(_resizeTimer, &QTimer::timeout, _resizeWidget, &QLabel::hide); } + _resizeWidget->setText(tr("Size: %1 x %2").arg(_columns).arg(_lines)); + _resizeWidget->move((width() - _resizeWidget->width()) / 2, + (height() - _resizeWidget->height()) / 2 + 20); + _resizeWidget->show(); + _resizeTimer->start(1000); } +} - // if the characters on the line are different in the old and the new _image - // then this line must be repainted. - if (updateLine) - { - // add the area occupied by this line to the region which needs to be - // repainted - QRect dirtyRect = QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*y , - _fontWidth * columnsToUpdate , - _fontHeight ); - - dirtyRegion |= dirtyRect; - } - - // replace the line of characters in the old _image with the - // current line of the new _image - memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); - } - - // if the new _image is smaller than the previous _image, then ensure that the area - // outside the new _image is cleared - if ( linesToUpdate < _usedLines ) - { - dirtyRegion |= QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*linesToUpdate , - _fontWidth * this->_columns , - _fontHeight * (_usedLines-linesToUpdate) ); - } - _usedLines = linesToUpdate; - - if ( columnsToUpdate < _usedColumns ) - { - dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , - _topMargin+tLy , - _fontWidth * (_usedColumns-columnsToUpdate) , - _fontHeight * this->_lines ); - } - _usedColumns = columnsToUpdate; - - dirtyRegion |= _inputMethodData.previousPreeditRect; - - // update the parts of the display which have changed - update(dirtyRegion); - - if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); - if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } - delete[] dirtyMask; - delete[] disstrU; -} - -void TerminalDisplay::showResizeNotification() -{ - if (_terminalSizeHint && isVisible()) - { - if (_terminalSizeStartup) { - _terminalSizeStartup=false; - return; - } - if (!_resizeWidget) - { - const QString label = tr("Size: XXX x XXX"); - _resizeWidget = new QLabel(label, this); - _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().horizontalAdvance(label)); - _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); - _resizeWidget->setAlignment(Qt::AlignCenter); - - _resizeWidget->setStyleSheet(QLatin1String("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark);color:palette(windowText);")); - - _resizeTimer = new QTimer(this); - _resizeTimer->setSingleShot(true); - connect(_resizeTimer, &QTimer::timeout, _resizeWidget, &QLabel::hide); - } - _resizeWidget->setText(tr("Size: %1 x %2").arg(_columns).arg(_lines)); - _resizeWidget->move((width()-_resizeWidget->width())/2, - (height()-_resizeWidget->height())/2+20); - _resizeWidget->show(); - _resizeTimer->start(1000); - } -} - -void TerminalDisplay::setBlinkingCursor(bool blink) -{ - _hasBlinkingCursor=blink; +void TerminalDisplay::setBlinkingCursor(bool blink) { + _hasBlinkingCursor = blink; - if (blink && !_blinkCursorTimer->isActive()) - _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); + if (blink && !_blinkCursorTimer->isActive()) + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); - if (!blink && _blinkCursorTimer->isActive()) - { - _blinkCursorTimer->stop(); - if (_cursorBlinking) - blinkCursorEvent(); - else - _cursorBlinking = false; - } + if (!blink && _blinkCursorTimer->isActive()) { + _blinkCursorTimer->stop(); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; + } } -void TerminalDisplay::setBlinkingTextEnabled(bool blink) -{ +void TerminalDisplay::setBlinkingTextEnabled(bool blink) { _allowBlinkingText = blink; if (blink && !_blinkTimer->isActive()) _blinkTimer->start(TEXT_BLINK_DELAY); - if (!blink && _blinkTimer->isActive()) - { + if (!blink && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } } -void TerminalDisplay::focusOutEvent(QFocusEvent*) -{ +void TerminalDisplay::focusOutEvent(QFocusEvent *) { emit termLostFocus(); // trigger a repaint of the cursor so that it is both visible (in case // it was hidden during blinking) @@ -1535,11 +1499,9 @@ void TerminalDisplay::focusOutEvent(QFocusEvent*) _blinkTimer->stop(); } -void TerminalDisplay::focusInEvent(QFocusEvent*) -{ +void TerminalDisplay::focusInEvent(QFocusEvent *) { emit termGetFocus(); - if (_hasBlinkingCursor) - { + if (_hasBlinkingCursor) { _blinkCursorTimer->start(); } updateCursor(); @@ -1548,175 +1510,153 @@ void TerminalDisplay::focusInEvent(QFocusEvent*) _blinkTimer->start(); } -void TerminalDisplay::paintEvent( QPaintEvent* pe ) -{ - QPainter paint(this); - QRect cr = contentsRect(); - - QPixmap currentBackgroundImage = _backgroundImage; - if(_backgroundMovie != nullptr) { - currentBackgroundImage = _backgroundMovie->currentPixmap(); - } - if(_backgroundVideoPlayer->isPlaying()) { - currentBackgroundImage = _backgroundVideoFrame; - } - - if ( !currentBackgroundImage.isNull() ) - { - QColor background = _colorTable[DEFAULT_BACK_COLOR].color; - if (_opacity < static_cast(1)) - { - background.setAlphaF(_opacity); - paint.save(); - paint.setCompositionMode(QPainter::CompositionMode_Source); - paint.fillRect(cr, background); - paint.restore(); +void TerminalDisplay::paintEvent(QPaintEvent *pe) { + QPainter paint(this); + QRect cr = contentsRect(); + + QPixmap currentBackgroundImage = _backgroundImage; + if (_backgroundMovie != nullptr) { + currentBackgroundImage = _backgroundMovie->currentPixmap(); } - else - { - paint.fillRect(cr, background); + if (_backgroundVideoPlayer->isPlaying()) { + currentBackgroundImage = _backgroundVideoFrame; } - paint.save(); - paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - - if (_backgroundMode == Stretch) - { // scale the image without keeping its proportions to fill the screen - paint.drawPixmap(cr, currentBackgroundImage, currentBackgroundImage.rect()); - } - else if (_backgroundMode == Zoom) - { // zoom in/out the image to fit it - QRect r = currentBackgroundImage.rect(); - qreal wRatio = static_cast(cr.width()) / r.width(); - qreal hRatio = static_cast(cr.height()) / r.height(); - if (wRatio > hRatio) - { - r.setWidth(qRound(r.width() * hRatio)); - r.setHeight(cr.height()); - } - else - { - r.setHeight(qRound(r.height() * wRatio)); - r.setWidth(cr.width()); + if (!currentBackgroundImage.isNull()) { + QColor background = _colorTable[DEFAULT_BACK_COLOR].color; + if (_opacity < static_cast(1)) { + background.setAlphaF(_opacity); + paint.save(); + paint.setCompositionMode(QPainter::CompositionMode_Source); + paint.fillRect(cr, background); + paint.restore(); + } else { + paint.fillRect(cr, background); } - r.moveCenter(cr.center()); - paint.drawPixmap(r, currentBackgroundImage, currentBackgroundImage.rect()); - } - else if (_backgroundMode == Fit) - { // if the image is bigger than the terminal, zoom it out to fit it - QRect r = currentBackgroundImage.rect(); - qreal wRatio = static_cast(cr.width()) / r.width(); - qreal hRatio = static_cast(cr.height()) / r.height(); - if (r.width() > cr.width()) - { - if (wRatio <= hRatio) - { + + paint.save(); + paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + + if (_backgroundMode == Stretch) { // scale the image without keeping its + // proportions to fill the screen + paint.drawPixmap(cr, currentBackgroundImage, currentBackgroundImage.rect()); + } else if (_backgroundMode == Zoom) { // zoom in/out the image to fit it + QRect r = currentBackgroundImage.rect(); + qreal wRatio = static_cast(cr.width()) / r.width(); + qreal hRatio = static_cast(cr.height()) / r.height(); + if (wRatio > hRatio) { + r.setWidth(qRound(r.width() * hRatio)); + r.setHeight(cr.height()); + } else { r.setHeight(qRound(r.height() * wRatio)); r.setWidth(cr.width()); } - else - { + r.moveCenter(cr.center()); + paint.drawPixmap(r, currentBackgroundImage, + currentBackgroundImage.rect()); + } else if (_backgroundMode == Fit) { // if the image is bigger than the + // terminal, zoom it out to fit it + QRect r = currentBackgroundImage.rect(); + qreal wRatio = static_cast(cr.width()) / r.width(); + qreal hRatio = static_cast(cr.height()) / r.height(); + if (r.width() > cr.width()) { + if (wRatio <= hRatio) { + r.setHeight(qRound(r.height() * wRatio)); + r.setWidth(cr.width()); + } else { + r.setWidth(qRound(r.width() * hRatio)); + r.setHeight(cr.height()); + } + } else if (r.height() > cr.height()) { r.setWidth(qRound(r.width() * hRatio)); r.setHeight(cr.height()); } - } - else if (r.height() > cr.height()) - { - r.setWidth(qRound(r.width() * hRatio)); - r.setHeight(cr.height()); - } - r.moveCenter(cr.center()); - paint.drawPixmap(r, currentBackgroundImage, currentBackgroundImage.rect()); - } - else if (_backgroundMode == Center) - { // center the image without scaling/zooming - QRect r = currentBackgroundImage.rect(); - r.moveCenter(cr.center()); - paint.drawPixmap(r.topLeft(), currentBackgroundImage); - } - else if (_backgroundMode == Tile) - { // tile the image - QPixmap scaled = currentBackgroundImage; - qreal wRatio = static_cast(cr.width()) / currentBackgroundImage.width(); - qreal hRatio = static_cast(cr.height()) / currentBackgroundImage.height(); - if(wRatio < 1.0 || hRatio < 1.0) - { - if (wRatio > hRatio) { - scaled = currentBackgroundImage.scaled(currentBackgroundImage.width() * hRatio, currentBackgroundImage.height() * hRatio); - } else { - scaled = currentBackgroundImage.scaled(currentBackgroundImage.width() * wRatio, currentBackgroundImage.height() * wRatio); + r.moveCenter(cr.center()); + paint.drawPixmap(r, currentBackgroundImage, currentBackgroundImage.rect()); + } else if (_backgroundMode == + Center) { // center the image without scaling/zooming + QRect r = currentBackgroundImage.rect(); + r.moveCenter(cr.center()); + paint.drawPixmap(r.topLeft(), currentBackgroundImage); + } else if (_backgroundMode == Tile) { // tile the image + QPixmap scaled = currentBackgroundImage; + qreal wRatio = + static_cast(cr.width()) / currentBackgroundImage.width(); + qreal hRatio = + static_cast(cr.height()) / currentBackgroundImage.height(); + if (wRatio < 1.0 || hRatio < 1.0) { + if (wRatio > hRatio) { + scaled = currentBackgroundImage.scaled( + currentBackgroundImage.width() * hRatio, + currentBackgroundImage.height() * hRatio); + } else { + scaled = currentBackgroundImage.scaled( + currentBackgroundImage.width() * wRatio, + currentBackgroundImage.height() * wRatio); + } } - } - int x = 0; - int y = 0; - while (y < cr.height()) - { - while (x < cr.width()) - { - paint.drawPixmap(x, y, scaled); - x += scaled.width(); + int x = 0; + int y = 0; + while (y < cr.height()) { + while (x < cr.width()) { + paint.drawPixmap(x, y, scaled); + x += scaled.width(); + } + x = 0; + y += scaled.height(); } - x = 0; - y += scaled.height(); + } else // if (_backgroundMode == None) + { + paint.drawPixmap(0, 0, currentBackgroundImage); } - } - else //if (_backgroundMode == None) - { - paint.drawPixmap(0, 0, currentBackgroundImage); - } - paint.restore(); - } + paint.restore(); + } - if(_drawTextTestFlag) - { - calDrawTextAdditionHeight(paint); - } + if (_drawTextTestFlag) { + calDrawTextAdditionHeight(paint); + } - const QRegion regToDraw = pe->region() & cr; - for (auto rect = regToDraw.begin(); rect != regToDraw.end(); rect++) - { - drawBackground(paint,*rect,_colorTable[DEFAULT_BACK_COLOR].color, - true /* use opacity setting */); - drawContents(paint, *rect); - } - drawInputMethodPreeditString(paint,preeditRect()); + const QRegion regToDraw = pe->region() & cr; + for (auto rect = regToDraw.begin(); rect != regToDraw.end(); rect++) { + drawBackground(paint, *rect, _colorTable[DEFAULT_BACK_COLOR].color, + true /* use opacity setting */); + drawContents(paint, *rect); + } + drawInputMethodPreeditString(paint, preeditRect()); - if(_isLocked) { - paint.save(); - paint.setOpacity(0.3); - paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - paint.drawPixmap(cr, _lockbackgroundImage, _lockbackgroundImage.rect()); - paint.restore(); - } + if (_isLocked) { + paint.save(); + paint.setOpacity(0.3); + paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + paint.drawPixmap(cr, _lockbackgroundImage, _lockbackgroundImage.rect()); + paint.restore(); + } - paintFilters(paint); + paintFilters(paint); } -QPoint TerminalDisplay::cursorPosition() const -{ +QPoint TerminalDisplay::cursorPosition() const { if (_screenWindow) return _screenWindow->cursorPosition(); else - return {0,0}; + return {0, 0}; } -QRect TerminalDisplay::preeditRect() const -{ - const int preeditLength = CharWidth::string_unicode_width(_inputMethodData.preeditString); +QRect TerminalDisplay::preeditRect() const { + const int preeditLength = + CharWidth::string_unicode_width(_inputMethodData.preeditString); - if ( preeditLength == 0 ) + if (preeditLength == 0) return {}; - return QRect(_leftMargin + _fontWidth*cursorPosition().x(), - _topMargin + _fontHeight*cursorPosition().y(), - _fontWidth*preeditLength, - _fontHeight); + return QRect(_leftMargin + _fontWidth * cursorPosition().x(), + _topMargin + _fontHeight * cursorPosition().y(), + _fontWidth * preeditLength, _fontHeight); } -void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) -{ - if ( _inputMethodData.preeditString.empty() ) +void TerminalDisplay::drawInputMethodPreeditString(QPainter &painter, const QRect &rect) { + if (_inputMethodData.preeditString.empty()) return; bool invertColors = false; @@ -1724,103 +1664,102 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color; Character style; style.character = ' '; - style.foregroundColor = CharacterColor(COLOR_SPACE_RGB,_colorTable[_preeditColorIndex].color); - style.backgroundColor = CharacterColor(COLOR_SPACE_RGB,_colorTable[DEFAULT_BACK_COLOR].color); + style.foregroundColor = + CharacterColor(COLOR_SPACE_RGB, _colorTable[_preeditColorIndex].color); + style.backgroundColor = + CharacterColor(COLOR_SPACE_RGB, _colorTable[DEFAULT_BACK_COLOR].color); style.rendition = DEFAULT_RENDITION; - drawBackground(painter,rect,background,true); - drawCursor(painter,rect,foreground,background,invertColors,true); + drawBackground(painter, rect, background, true); + drawCursor(painter, rect, foreground, background, invertColors, true); invertColors = false; - drawCharacters(painter,rect,_inputMethodData.preeditString,&style,invertColors); + drawCharacters(painter, rect, _inputMethodData.preeditString, &style, + invertColors); _inputMethodData.previousPreeditRect = rect; } -FilterChain* TerminalDisplay::filterChain() const -{ - return _filterChain; -} +FilterChain *TerminalDisplay::filterChain() const { return _filterChain; } -void TerminalDisplay::paintFilters(QPainter& painter) -{ +void TerminalDisplay::paintFilters(QPainter &painter) { // get color of character under mouse and use it to draw // lines for filters QPoint cursorPos = mapFromGlobal(QCursor::pos()); int cursorLine; int cursorColumn; - int leftMargin = _leftBaseMargin - + ((_scrollbarLocation == QTermWidget::ScrollBarLeft - && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) - ? _scrollBar->width() : 0); + int leftMargin = _leftBaseMargin + + ((_scrollbarLocation == QTermWidget::ScrollBarLeft && + !_scrollBar->style()->styleHint( + QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? _scrollBar->width() + : 0); - getCharacterPosition( cursorPos , cursorLine , cursorColumn ); - Character cursorCharacter = _image[loc(cursorColumn,cursorLine)]; + getCharacterPosition(cursorPos, cursorLine, cursorColumn); + Character cursorCharacter = _image[loc(cursorColumn, cursorLine)]; - painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) ); + painter.setPen(QPen(cursorCharacter.foregroundColor.color(colorTable()))); // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot - QList spots = _filterChain->hotSpots(); - QListIterator iter(spots); - while (iter.hasNext()) - { - Filter::HotSpot* spot = iter.next(); + QList spots = _filterChain->hotSpots(); + QListIterator iter(spots); + while (iter.hasNext()) { + Filter::HotSpot *spot = iter.next(); QRegion region; - if ( spot->type() == Filter::HotSpot::Link ) { + if (spot->type() == Filter::HotSpot::Link) { QRect r; - if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, - spot->startLine()*_fontHeight + 1 + _topBaseMargin, - spot->endColumn()*_fontWidth - 1 + leftMargin, - (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); + if (spot->startLine() == spot->endLine()) { + r.setCoords(spot->startColumn() * _fontWidth + 1 + leftMargin, + spot->startLine() * _fontHeight + 1 + _topBaseMargin, + spot->endColumn() * _fontWidth - 1 + leftMargin, + (spot->endLine() + 1) * _fontHeight - 1 + _topBaseMargin); region |= r; } else { - r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, - spot->startLine()*_fontHeight + 1 + _topBaseMargin, - _columns*_fontWidth - 1 + leftMargin, - (spot->startLine()+1)*_fontHeight - 1 + _topBaseMargin ); + r.setCoords(spot->startColumn() * _fontWidth + 1 + leftMargin, + spot->startLine() * _fontHeight + 1 + _topBaseMargin, + _columns * _fontWidth - 1 + leftMargin, + (spot->startLine() + 1) * _fontHeight - 1 + _topBaseMargin); region |= r; - for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + 1 + leftMargin, - line*_fontHeight + 1 + _topBaseMargin, - _columns*_fontWidth - 1 + leftMargin, - (line+1)*_fontHeight - 1 + _topBaseMargin ); + for (int line = spot->startLine() + 1; line < spot->endLine(); line++) { + r.setCoords(0 * _fontWidth + 1 + leftMargin, + line * _fontHeight + 1 + _topBaseMargin, + _columns * _fontWidth - 1 + leftMargin, + (line + 1) * _fontHeight - 1 + _topBaseMargin); region |= r; } - r.setCoords( 0*_fontWidth + 1 + leftMargin, - spot->endLine()*_fontHeight + 1 + _topBaseMargin, - spot->endColumn()*_fontWidth - 1 + leftMargin, - (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); + r.setCoords(0 * _fontWidth + 1 + leftMargin, + spot->endLine() * _fontHeight + 1 + _topBaseMargin, + spot->endColumn() * _fontWidth - 1 + leftMargin, + (spot->endLine() + 1) * _fontHeight - 1 + _topBaseMargin); region |= r; } } - for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) - { + for (int line = spot->startLine(); line <= spot->endLine(); line++) { int startColumn = 0; - int endColumn = _columns-1; // TODO use number of _columns which are actually - // occupied on this line rather than the width of the - // display in _columns + int endColumn = _columns - 1; // TODO use number of _columns which are + // actually occupied on this line rather + // than the width of the display in _columns // ignore whitespace at the end of the lines do { - if(endColumn <= 0) - break; - if( _image[loc(startColumn,line)].character > 0xffff ) - break; - if( QChar(_image[loc(startColumn,line)].character).isSpace() ) - break; - endColumn--; - } while ( true ); + if (endColumn <= 0) + break; + if (_image[loc(startColumn, line)].character > 0xffff) + break; + if (QChar(_image[loc(startColumn, line)].character).isSpace()) + break; + endColumn--; + } while (true); // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; - if ( line == spot->startLine() ) + if (line == spot->startLine()) startColumn = spot->startColumn(); - if ( line == spot->endLine() ) + if (line == spot->endLine()) endColumn = spot->endColumn(); // subtract one pixel from @@ -1833,919 +1772,898 @@ void TerminalDisplay::paintFilters(QPainter& painter) // because the check below for the position of the cursor // finds it on the border of the target area QRect r; - r.setCoords( startColumn*_fontWidth + 1 + leftMargin, - line*_fontHeight + 1 + _topBaseMargin, - endColumn*_fontWidth - 1 + leftMargin, - (line+1)*_fontHeight - 1 + _topBaseMargin ); + r.setCoords(startColumn * _fontWidth + 1 + leftMargin, + line * _fontHeight + 1 + _topBaseMargin, + endColumn * _fontWidth - 1 + leftMargin, + (line + 1) * _fontHeight - 1 + _topBaseMargin); // Underline link hotspots - if ( spot->type() == Filter::HotSpot::Link ) - { + if (spot->type() == Filter::HotSpot::Link) { QFontMetrics metrics(font()); - // find the baseline (which is the invisible line that the characters in the font sit on, - // with some having tails dangling below) + // find the baseline (which is the invisible line that the characters in + // the font sit on, with some having tails dangling below) int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that int underlinePos = baseline + metrics.underlinePos(); - if ( region.contains( mapFromGlobal(QCursor::pos()) ) ){ - painter.drawLine( r.left() , underlinePos , - r.right() , underlinePos ); + if (region.contains(mapFromGlobal(QCursor::pos()))) { + painter.drawLine(r.left(), underlinePos, r.right(), underlinePos); } } // Marker hotspots simply have a transparent rectanglular shape // drawn on top of them - else if ( spot->type() == Filter::HotSpot::Marker ) - { + else if (spot->type() == Filter::HotSpot::Marker) { QColor markerColor = spot->color(); markerColor.setAlpha(120); - painter.fillRect( r , markerColor ); + painter.fillRect(r, markerColor); } } } } -int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const -{ - QFontMetrics fm(font()); - int result = 0; - for (int column = 0; column < length; column++) { - result += fm.horizontalAdvance(QChar(static_cast(_image[loc(startColumn + column, line)].character))); - } - return result; -} - -QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length) { - int left = _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line); - int top = _fontHeight * line; - int width = _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line); - return {_leftMargin + topLeftX + left, - _topMargin + topLeftY + top, - width, - _fontHeight}; +int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const { + QFontMetrics fm(font()); + int result = 0; + for (int column = 0; column < length; column++) { + result += fm.horizontalAdvance(QChar(static_cast( + _image[loc(startColumn + column, line)].character))); + } + return result; } -void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) -{ - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); - - int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); - int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); - int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); - int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); - - const int bufferSize = _usedColumns; - std::wstring unistr; - unistr.reserve(bufferSize); - for (int y = luy; y <= rly; y++) - { - quint32 c = _image[loc(lux,y)].character; - int x = lux; - if(!c && x) - x--; // Search for start of multi-column character - for (; x <= rlx; x++) - { - int len = 1; - int p = 0; - - // reset our buffer to the maximal size - unistr.resize(bufferSize); - - // is this a single character or a sequence of characters ? - if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) - { - // sequence of characters - ushort extendedCharLength = 0; - ushort* chars = ExtendedCharTable::instance - .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); - for ( int index = 0 ; index < extendedCharLength ; index++ ) - { - Q_ASSERT( p < bufferSize ); - unistr[p++] = chars[index]; - } - } - else - { - // single character - c = _image[loc(x,y)].character; - if (c) - { - Q_ASSERT( p < bufferSize ); - unistr[p++] = c; //fontMap(c); - } - } - - bool lineDraw = isLineChar(c); - bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0); - CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; - CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; - quint8 currentRendition = _image[loc(x,y)].rendition; - - while (x+len <= rlx && - _image[loc(x+len,y)].foregroundColor == currentForeground && - _image[loc(x+len,y)].backgroundColor == currentBackground && - _image[loc(x+len,y)].rendition == currentRendition && - (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && - isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment! - { - if (c) - unistr[p++] = c; //fontMap(c); - if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition - len++; // Skip trailing part of multi-column character - len++; - } - if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) - len++; // Adjust for trailing part of multi-column character +QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, + int startColumn, int line, + int length) { + int left = + _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line); + int top = _fontHeight * line; + int width = + _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line); + return {_leftMargin + topLeftX + left, _topMargin + topLeftY + top, width, + _fontHeight}; +} + +void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) { + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + + int lux = qMin(_usedColumns - 1, qMax(0, (rect.left() - tLx - _leftMargin) / _fontWidth)); + int luy = qMin(_usedLines - 1, qMax(0, (rect.top() - tLy - _topMargin) / _fontHeight)); + int rlx = qMin(_usedColumns - 1, qMax(0, (rect.right() - tLx - _leftMargin) / _fontWidth)); + int rly = qMin(_usedLines - 1, qMax(0, (rect.bottom() - tLy - _topMargin) / _fontHeight)); + + const int bufferSize = _usedColumns; + std::wstring unistr; + unistr.reserve(bufferSize); + for (int y = luy; y <= rly; y++) { + quint32 c = _image[loc(lux, y)].character; + int x = lux; + if (!c && x) + x--; // Search for start of multi-column character + for (; x <= rlx; x++) { + int len = 1; + int p = 0; + + // reset our buffer to the maximal size + unistr.resize(bufferSize); + + // is this a single character or a sequence of characters ? + if (_image[loc(x, y)].rendition & RE_EXTENDED_CHAR) { + // sequence of characters + ushort extendedCharLength = 0; + ushort *chars = ExtendedCharTable::instance.lookupExtendedChar( + _image[loc(x, y)].charSequence, extendedCharLength); + for (int index = 0; index < extendedCharLength; index++) { + Q_ASSERT(p < bufferSize); + unistr[p++] = chars[index]; + } + } else { + // single character + c = _image[loc(x, y)].character; + if (c) { + Q_ASSERT(p < bufferSize); + unistr[p++] = c; // fontMap(c); + } + } + + bool lineDraw = isLineChar(c); + bool doubleWidth = + (_image[qMin(loc(x, y) + 1, _imageSize)].character == 0); + CharacterColor currentForeground = _image[loc(x, y)].foregroundColor; + CharacterColor currentBackground = _image[loc(x, y)].backgroundColor; + quint8 currentRendition = _image[loc(x, y)].rendition; + + while (x + len <= rlx && + _image[loc(x + len, y)].foregroundColor == currentForeground && + _image[loc(x + len, y)].backgroundColor == currentBackground && + _image[loc(x + len, y)].rendition == currentRendition && + (_image[qMin(loc(x + len, y) + 1, _imageSize)].character == 0) == + doubleWidth && + isLineChar(c = _image[loc(x + len, y)].character) == + lineDraw) // Assignment! + { + if (c) + unistr[p++] = c; // fontMap(c); + if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see + // above if condition + len++; // Skip trailing part of multi-column character + len++; + } + if ((x + len < _usedColumns) && (!_image[loc(x + len, y)].character)) + len++; // Adjust for trailing part of multi-column character bool save__fixedFont = _fixedFont; - if (lineDraw) - _fixedFont = false; - unistr.resize(p); + if (lineDraw) + _fixedFont = false; + unistr.resize(p); - // Create a text scaling matrix for double width and double height lines. - QTransform textScale; + // Create a text scaling matrix for double width and double height lines. + QTransform textScale; - if (y < _lineProperties.size()) - { - if (_lineProperties[y] & LINE_DOUBLEWIDTH) - textScale.scale(2,1); + if (y < _lineProperties.size()) { + if (_lineProperties[y] & LINE_DOUBLEWIDTH) + textScale.scale(2, 1); - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) - textScale.scale(1,2); - } + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + textScale.scale(1, 2); + } - //Apply text scaling matrix. - paint.setWorldTransform(textScale, true); + // Apply text scaling matrix. + paint.setWorldTransform(textScale, true); - //calculate the area in which the text will be drawn - QRect textArea = calculateTextArea(tLx, tLy, x, y, len); + // calculate the area in which the text will be drawn + QRect textArea = calculateTextArea(tLx, tLy, x, y, len); - //move the calculated area to take account of scaling applied to the painter. - //the position of the area from the origin (0,0) is scaled - //by the opposite of whatever - //transformation has been applied to the painter. this ensures that - //painting does actually start from textArea.topLeft() - //(instead of textArea.topLeft() * painter-scale) - textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); + // move the calculated area to take account of scaling applied to the + // painter. the position of the area from the origin (0,0) is scaled by + // the opposite of whatever transformation has been applied to the + // painter. this ensures that painting does actually start from + // textArea.topLeft() (instead of textArea.topLeft() * painter-scale) + textArea.moveTopLeft(textScale.inverted().map(textArea.topLeft())); - //paint text fragment - drawTextFragment( paint, - textArea, - unistr, - &_image[loc(x,y)] , - _screenWindow->isSelected(x,y) - ); + // paint text fragment + drawTextFragment(paint, textArea, unistr, &_image[loc(x, y)], _screenWindow->isSelected(x, y)); - _fixedFont = save__fixedFont; + _fixedFont = save__fixedFont; - //reset back to single-width, single-height _lines - paint.setWorldTransform(textScale.inverted(), true); + // reset back to single-width, single-height _lines + paint.setWorldTransform(textScale.inverted(), true); - if (y < _lineProperties.size()-1) - { - //double-height _lines are represented by two adjacent _lines - //containing the same characters - //both _lines will have the LINE_DOUBLEHEIGHT attribute. - //If the current line has the LINE_DOUBLEHEIGHT attribute, - //we can therefore skip the next line - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) - y++; - } + if (y < _lineProperties.size() - 1) { + // double-height _lines are represented by two adjacent _lines + // containing the same characters + // both _lines will have the LINE_DOUBLEHEIGHT attribute. + // If the current line has the LINE_DOUBLEHEIGHT attribute, + // we can therefore skip the next line + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + y++; + } - x += len - 1; + x += len - 1; + } } - } } -void TerminalDisplay::blinkEvent() -{ - if (!_allowBlinkingText) return; +void TerminalDisplay::blinkEvent() { + if (!_allowBlinkingText) + return; - _blinking = !_blinking; + _blinking = !_blinking; - //TODO: Optimize to only repaint the areas of the widget - // where there is blinking text - // rather than repainting the whole widget. - update(); + // TODO: Optimize to only repaint the areas of the widget + // where there is blinking text + // rather than repainting the whole widget. + update(); } -QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const -{ +QRect TerminalDisplay::imageToWidget(const QRect &imageArea) const { QRect result; - result.setLeft( _leftMargin + _fontWidth * imageArea.left() ); - result.setTop( _topMargin + _fontHeight * imageArea.top() ); - result.setWidth( _fontWidth * imageArea.width() ); - result.setHeight( _fontHeight * imageArea.height() ); + result.setLeft(_leftMargin + _fontWidth * imageArea.left()); + result.setTop(_topMargin + _fontHeight * imageArea.top()); + result.setWidth(_fontWidth * imageArea.width()); + result.setHeight(_fontHeight * imageArea.height()); return result; } -void TerminalDisplay::updateCursor() -{ - QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); - update(cursorRect); +void TerminalDisplay::updateCursor() { + QRect cursorRect = imageToWidget(QRect(cursorPosition(), QSize(1, 1))); + update(cursorRect); } -void TerminalDisplay::blinkCursorEvent() -{ - _cursorBlinking = !_cursorBlinking; - updateCursor(); +void TerminalDisplay::blinkCursorEvent() { + _cursorBlinking = !_cursorBlinking; + updateCursor(); } -/* ------------------------------------------------------------------------- */ -/* */ -/* Resizing */ -/* */ -/* ------------------------------------------------------------------------- */ -void TerminalDisplay::resizeEvent(QResizeEvent*) -{ - updateImageSize(); - processFilters(); +void TerminalDisplay::resizeEvent(QResizeEvent *) { + updateImageSize(); + processFilters(); } -void TerminalDisplay::propagateSize() -{ - if (_isFixedSize) - { - setSize(_columns, _lines); - QWidget::setFixedSize(sizeHint()); - parentWidget()->adjustSize(); - parentWidget()->setFixedSize(parentWidget()->sizeHint()); - return; - } - if (_image) - updateImageSize(); -} - -void TerminalDisplay::updateImageSize() -{ - Character* oldimg = _image; - int oldlin = _lines; - int oldcol = _columns; +void TerminalDisplay::propagateSize() { + if (_isFixedSize) { + setSize(_columns, _lines); + QWidget::setFixedSize(sizeHint()); + parentWidget()->adjustSize(); + parentWidget()->setFixedSize(parentWidget()->sizeHint()); + return; + } + if (_image) + updateImageSize(); +} - makeImage(); +void TerminalDisplay::updateImageSize() { + Character *oldimg = _image; + int oldlin = _lines; + int oldcol = _columns; - // copy the old image to reduce flicker - int lines = qMin(oldlin,_lines); - int columns = qMin(oldcol,_columns); + makeImage(); - if (oldimg) - { - for (int line = 0; line < lines; line++) - { - memcpy((void*)&_image[_columns*line], - (void*)&oldimg[oldcol*line],columns*sizeof(Character)); + // copy the old image to reduce flicker + int lines = qMin(oldlin, _lines); + int columns = qMin(oldcol, _columns); + + if (oldimg) { + for (int line = 0; line < lines; line++) { + memcpy((void *)&_image[_columns * line], (void *)&oldimg[oldcol * line], + columns * sizeof(Character)); + } + delete[] oldimg; } - delete[] oldimg; - } - if (_screenWindow) - _screenWindow->setWindowLines(_lines); + if (_screenWindow) + _screenWindow->setWindowLines(_lines); - _resizing = (oldlin!=_lines) || (oldcol!=_columns); + _resizing = (oldlin != _lines) || (oldcol != _columns); - if ( _resizing ) - { - if(_showResizeNotificationEnabled) - showResizeNotification(); - emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent - emit changedContentCountSignal(_lines, _columns); - } + if (_resizing) { + if (_showResizeNotificationEnabled) + showResizeNotification(); + emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent + emit changedContentCountSignal(_lines, _columns); + } - _resizing = false; + _resizing = false; } -//showEvent and hideEvent are reimplemented here so that it appears to other classes that the -//display has been resized when the display is hidden or shown. +// showEvent and hideEvent are reimplemented here so that it appears to other +// classes that the display has been resized when the display is hidden or +// shown. // -//TODO: Perhaps it would be better to have separate signals for show and hide instead of using -//the same signal as the one for a content size change -void TerminalDisplay::showEvent(QShowEvent*) -{ - emit changedContentSizeSignal(_contentHeight,_contentWidth); -} -void TerminalDisplay::hideEvent(QHideEvent*) -{ - emit changedContentSizeSignal(_contentHeight,_contentWidth); +// TODO: Perhaps it would be better to have separate signals for show and hide +// instead of using the same signal as the one for a content size change +void TerminalDisplay::showEvent(QShowEvent *) { + emit changedContentSizeSignal(_contentHeight, _contentWidth); } -/* ------------------------------------------------------------------------- */ -/* */ -/* Scrollbar */ -/* */ -/* ------------------------------------------------------------------------- */ +void TerminalDisplay::hideEvent(QHideEvent *) { + emit changedContentSizeSignal(_contentHeight, _contentWidth); +} -void TerminalDisplay::scrollBarPositionChanged(int) -{ - if ( !_screenWindow ) - return; +void TerminalDisplay::scrollBarPositionChanged(int) { + if (!_screenWindow) + return; - _screenWindow->scrollTo( _scrollBar->value() ); + _screenWindow->scrollTo(_scrollBar->value()); - // if the thumb has been moved to the bottom of the _scrollBar then set - // the display to automatically track new output, - // that is, scroll down automatically - // to how new _lines as they are added - const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); - _screenWindow->setTrackOutput( atEndOfOutput ); + // if the thumb has been moved to the bottom of the _scrollBar then set + // the display to automatically track new output, + // that is, scroll down automatically + // to how new _lines as they are added + const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); + _screenWindow->setTrackOutput(atEndOfOutput); - updateImage(); + updateImage(); } -void TerminalDisplay::setScroll(int cursor, int slines) -{ - // update _scrollBar if the range or value has changed, - // otherwise return - // - // setting the range or value of a _scrollBar will always trigger - // a repaint, so it should be avoided if it is not necessary - if ( _scrollBar->minimum() == 0 && - _scrollBar->maximum() == (slines - _lines) && - _scrollBar->value() == cursor ) - { +void TerminalDisplay::setScroll(int cursor, int slines) { + // update _scrollBar if the range or value has changed, + // otherwise return + // + // setting the range or value of a _scrollBar will always trigger + // a repaint, so it should be avoided if it is not necessary + if (_scrollBar->minimum() == 0 && + _scrollBar->maximum() == (slines - _lines) && + _scrollBar->value() == cursor) { return; - } + } - disconnect(_scrollBar, &QScrollBar::valueChanged, this, &TerminalDisplay::scrollBarPositionChanged); - _scrollBar->setRange(0,slines - _lines); - _scrollBar->setSingleStep(1); - _scrollBar->setPageStep(_lines); - _scrollBar->setValue(cursor); - connect(_scrollBar, &QScrollBar::valueChanged, this, &TerminalDisplay::scrollBarPositionChanged); + disconnect(_scrollBar, &QScrollBar::valueChanged, this, + &TerminalDisplay::scrollBarPositionChanged); + _scrollBar->setRange(0, slines - _lines); + _scrollBar->setSingleStep(1); + _scrollBar->setPageStep(_lines); + _scrollBar->setValue(cursor); + connect(_scrollBar, &QScrollBar::valueChanged, this, + &TerminalDisplay::scrollBarPositionChanged); } -void TerminalDisplay::scrollToEnd() -{ - disconnect(_scrollBar, &QScrollBar::valueChanged, this, &TerminalDisplay::scrollBarPositionChanged); - _scrollBar->setValue( _scrollBar->maximum() ); - connect(_scrollBar, &QScrollBar::valueChanged, this, &TerminalDisplay::scrollBarPositionChanged); +void TerminalDisplay::scrollToEnd() { + disconnect(_scrollBar, &QScrollBar::valueChanged, this, + &TerminalDisplay::scrollBarPositionChanged); + _scrollBar->setValue(_scrollBar->maximum()); + connect(_scrollBar, &QScrollBar::valueChanged, this, + &TerminalDisplay::scrollBarPositionChanged); - _screenWindow->scrollTo( _scrollBar->value() + 1 ); - _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); + _screenWindow->scrollTo(_scrollBar->value() + 1); + _screenWindow->setTrackOutput(_screenWindow->atEndOfOutput()); } -void TerminalDisplay::setScrollBarPosition(QTermWidget::ScrollBarPosition position) -{ - if (_scrollbarLocation == position) - return; +void TerminalDisplay::setScrollBarPosition( + QTermWidget::ScrollBarPosition position) { + if (_scrollbarLocation == position) + return; - if ( position == QTermWidget::NoScrollBar ) - _scrollBar->hide(); - else - _scrollBar->show(); + if (position == QTermWidget::NoScrollBar) + _scrollBar->hide(); + else + _scrollBar->show(); - _topMargin = _leftMargin = 1; - _scrollbarLocation = position; + _topMargin = _leftMargin = 1; + _scrollbarLocation = position; - propagateSize(); - update(); + propagateSize(); + update(); } -void TerminalDisplay::mousePressEvent(QMouseEvent* ev) -{ - emit mousePressEventForwarded(ev); - - if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { - mouseTripleClickEvent(ev); - return; - } +void TerminalDisplay::mousePressEvent(QMouseEvent *ev) { + emit mousePressEventForwarded(ev); - if ( !contentsRect().contains(ev->pos()) ) return; - - if ( !_screenWindow ) return; - - int charLine; - int charColumn; - getCharacterPosition(ev->pos(),charLine,charColumn); - QPoint pos = QPoint(charColumn,charLine); - - if ( ev->button() == Qt::LeftButton) - { - _lineSelectionMode = false; - _wordSelectionMode = false; - - emit isBusySelecting(true); // Keep it steady... - // Drag only when the Control key is hold - bool selected = false; + if (_possibleTripleClick && (ev->button() == Qt::LeftButton)) { + mouseTripleClickEvent(ev); + return; + } - // The receiver of the testIsSelected() signal will adjust - // 'selected' accordingly. - //emit testIsSelected(pos.x(), pos.y(), selected); + if (!contentsRect().contains(ev->pos())) + return; - selected = _screenWindow->isSelected(pos.x(),pos.y()); + if (!_screenWindow) + return; - if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { - // The user clicked inside selected text - if ((_mouseMarks) && (ev->modifiers() & Qt::ShiftModifier)){ - _screenWindow->clearSelection(); - if(shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { - shiftSelectionStartX = pos.x(); - shiftSelectionStartY = pos.y(); - } else { - _screenWindow->setSelectionStart(shiftSelectionStartX,shiftSelectionStartY,ev->modifiers() & Qt::AltModifier); - _screenWindow->setSelectionEnd(pos.x(),pos.y()); - } - } else { - shiftSelectionStartX = -1; - shiftSelectionStartY = -1; - dragInfo.state = diPending; - dragInfo.start = ev->pos(); - } - } else { - // No reason to ever start a drag event - dragInfo.state = diNone; - - _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) ); - _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier); - - if (_mouseMarks) { - if (ev->modifiers() & Qt::ShiftModifier) { - if(_screenWindow->isClearSelection()) { - // check - if(shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { - shiftSelectionStartX = pos.x(); - shiftSelectionStartY = pos.y(); + int charLine; + int charColumn; + getCharacterPosition(ev->pos(), charLine, charColumn); + QPoint pos = QPoint(charColumn, charLine); + + if (ev->button() == Qt::LeftButton) { + _lineSelectionMode = false; + _wordSelectionMode = false; + + emit isBusySelecting(true); // Keep it steady... + // Drag only when the Control key is hold + bool selected = false; + + // The receiver of the testIsSelected() signal will adjust + // 'selected' accordingly. + // emit testIsSelected(pos.x(), pos.y(), selected); + + selected = _screenWindow->isSelected(pos.x(), pos.y()); + + if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected) { + // The user clicked inside selected text + if ((_mouseMarks) && (ev->modifiers() & Qt::ShiftModifier)) { + _screenWindow->clearSelection(); + if (shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { + shiftSelectionStartX = pos.x(); + shiftSelectionStartY = pos.y(); + } else { + _screenWindow->setSelectionStart(shiftSelectionStartX, + shiftSelectionStartY, + ev->modifiers() & Qt::AltModifier); + _screenWindow->setSelectionEnd(pos.x(), pos.y()); + } } else { - _screenWindow->setSelectionStart(shiftSelectionStartX,shiftSelectionStartY,ev->modifiers() & Qt::AltModifier); - _screenWindow->setSelectionEnd(pos.x(),pos.y()); + shiftSelectionStartX = -1; + shiftSelectionStartY = -1; + dragInfo.state = diPending; + dragInfo.start = ev->pos(); } - } else { - _screenWindow->clearSelection(); - if(shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { - shiftSelectionStartX = pos.x(); - shiftSelectionStartY = pos.y(); + } else { + // No reason to ever start a drag event + dragInfo.state = diNone; + + _preserveLineBreaks = !((ev->modifiers() & Qt::ControlModifier) && + !(ev->modifiers() & Qt::AltModifier)); + _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && + (ev->modifiers() & Qt::ControlModifier); + + if (_mouseMarks) { + if (ev->modifiers() & Qt::ShiftModifier) { + if (_screenWindow->isClearSelection()) { + // check + if (shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { + shiftSelectionStartX = pos.x(); + shiftSelectionStartY = pos.y(); + } else { + _screenWindow->setSelectionStart( + shiftSelectionStartX, shiftSelectionStartY, + ev->modifiers() & Qt::AltModifier); + _screenWindow->setSelectionEnd(pos.x(), pos.y()); + } + } else { + _screenWindow->clearSelection(); + if (shiftSelectionStartX == -1 && shiftSelectionStartY == -1) { + shiftSelectionStartX = pos.x(); + shiftSelectionStartY = pos.y(); + } else { + _screenWindow->setSelectionStart( + shiftSelectionStartX, shiftSelectionStartY, + ev->modifiers() & Qt::AltModifier); + _screenWindow->setSelectionEnd(pos.x(), pos.y()); + } + } + } else { + _screenWindow->clearSelection(); + shiftSelectionStartX = -1; + shiftSelectionStartY = -1; + // emit clearSelectionSignal(); + pos.ry() += _scrollBar->value(); + _iPntSel = _pntSel = pos; + _actSel = 1; // left mouse button pressed but nothing selected yet. + } } else { - _screenWindow->setSelectionStart(shiftSelectionStartX,shiftSelectionStartY,ev->modifiers() & Qt::AltModifier); - _screenWindow->setSelectionEnd(pos.x(),pos.y()); + if (ev->modifiers() & Qt::ShiftModifier) { + _screenWindow->clearSelection(); + + // emit clearSelectionSignal(); + pos.ry() += _scrollBar->value(); + _iPntSel = _pntSel = pos; + _actSel = 1; // left mouse button pressed but nothing selected yet. + } else { + emit mouseSignal( + 0, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); + } + } + + if (ev->modifiers() & Qt::ControlModifier) { + Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); + if (spot && spot->type() == Filter::HotSpot::Link) { + if (spot->hasClickAction()) { + spot->clickAction(); + } + } } - } - } else { - _screenWindow->clearSelection(); - shiftSelectionStartX = -1; - shiftSelectionStartY = -1; - //emit clearSelectionSignal(); - pos.ry() += _scrollBar->value(); - _iPntSel = _pntSel = pos; - _actSel = 1; // left mouse button pressed but nothing selected yet. - } - } else { - if (ev->modifiers() & Qt::ShiftModifier){ - _screenWindow->clearSelection(); - - //emit clearSelectionSignal(); - pos.ry() += _scrollBar->value(); - _iPntSel = _pntSel = pos; - _actSel = 1; // left mouse button pressed but nothing selected yet. - } else { - emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } - } - - if (ev->modifiers() & Qt::ControlModifier) { - Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); - if (spot && spot->type() == Filter::HotSpot::Link) { - if(spot->hasClickAction()){ - spot->clickAction(); - } } - } + } else if (ev->button() == Qt::MiddleButton) { + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + emitSelection(true, ev->modifiers() & Qt::ControlModifier); + else + emit mouseSignal( + 1, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); + } else if (ev->button() == Qt::RightButton) { + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + emit configureRequest(ev->pos()); + else + emit mouseSignal( + 2, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } - } - else if ( ev->button() == Qt::MiddleButton ) - { - if ( _mouseMarks || (ev->modifiers() & Qt::ShiftModifier) ) - emitSelection(true,ev->modifiers() & Qt::ControlModifier); - else - emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } - else if ( ev->button() == Qt::RightButton ) - { - if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) - emit configureRequest(ev->pos()); - else - emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } } -QList TerminalDisplay::filterActions(const QPoint& position) -{ - int charLine, charColumn; - getCharacterPosition(position,charLine,charColumn); +QList TerminalDisplay::filterActions(const QPoint &position) { + int charLine, charColumn; + getCharacterPosition(position, charLine, charColumn); - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); - return spot ? spot->actions() : QList(); + return spot ? spot->actions() : QList(); } -void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) -{ - int charLine = 0; - int charColumn = 0; - int leftMargin = _leftBaseMargin - + ((_scrollbarLocation == QTermWidget::ScrollBarLeft - && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) - ? _scrollBar->width() : 0); - - getCharacterPosition(ev->pos(),charLine,charColumn); - - // handle filters - // change link hot-spot appearance on mouse-over - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); - if ( spot && spot->type() == Filter::HotSpot::Link) - { - QRegion previousHotspotArea = _mouseOverHotspotArea; - _mouseOverHotspotArea = QRegion(); - QRect r; - if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + leftMargin, - spot->startLine()*_fontHeight + _topBaseMargin, - spot->endColumn()*_fontWidth + leftMargin, - (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); - _mouseOverHotspotArea |= r; - } else { - r.setCoords( spot->startColumn()*_fontWidth + leftMargin, - spot->startLine()*_fontHeight + _topBaseMargin, - _columns*_fontWidth - 1 + leftMargin, - (spot->startLine()+1)*_fontHeight + _topBaseMargin ); - _mouseOverHotspotArea |= r; - for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + leftMargin, - line*_fontHeight + _topBaseMargin, - _columns*_fontWidth + leftMargin, - (line+1)*_fontHeight + _topBaseMargin ); +void TerminalDisplay::mouseMoveEvent(QMouseEvent *ev) { + int charLine = 0; + int charColumn = 0; + int leftMargin = _leftBaseMargin + + ((_scrollbarLocation == QTermWidget::ScrollBarLeft && + !_scrollBar->style()->styleHint( + QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? _scrollBar->width() + : 0); + + getCharacterPosition(ev->pos(), charLine, charColumn); + + // handle filters + // change link hot-spot appearance on mouse-over + Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); + if (spot && spot->type() == Filter::HotSpot::Link) { + QRegion previousHotspotArea = _mouseOverHotspotArea; + _mouseOverHotspotArea = QRegion(); + QRect r; + if (spot->startLine() == spot->endLine()) { + r.setCoords(spot->startColumn() * _fontWidth + leftMargin, + spot->startLine() * _fontHeight + _topBaseMargin, + spot->endColumn() * _fontWidth + leftMargin, + (spot->endLine() + 1) * _fontHeight - 1 + _topBaseMargin); + _mouseOverHotspotArea |= r; + } else { + r.setCoords(spot->startColumn() * _fontWidth + leftMargin, + spot->startLine() * _fontHeight + _topBaseMargin, + _columns * _fontWidth - 1 + leftMargin, + (spot->startLine() + 1) * _fontHeight + _topBaseMargin); + _mouseOverHotspotArea |= r; + for (int line = spot->startLine() + 1; line < spot->endLine(); line++) { + r.setCoords(0 * _fontWidth + leftMargin, + line * _fontHeight + _topBaseMargin, + _columns * _fontWidth + leftMargin, + (line + 1) * _fontHeight + _topBaseMargin); + _mouseOverHotspotArea |= r; + } + r.setCoords(0 * _fontWidth + leftMargin, + spot->endLine() * _fontHeight + _topBaseMargin, + spot->endColumn() * _fontWidth + leftMargin, + (spot->endLine() + 1) * _fontHeight + _topBaseMargin); _mouseOverHotspotArea |= r; } - r.setCoords( 0*_fontWidth + leftMargin, - spot->endLine()*_fontHeight + _topBaseMargin, - spot->endColumn()*_fontWidth + leftMargin, - (spot->endLine()+1)*_fontHeight + _topBaseMargin ); - _mouseOverHotspotArea |= r; - } - update( _mouseOverHotspotArea | previousHotspotArea ); - if ( _mouseOverHotspotArea.contains(ev->pos()) ) - { - if ( spot && spot->type() == Filter::HotSpot::Link && spot->hasClickAction()) { - QPoint globalPos = mapToGlobal(ev->pos()); - QToolTip::showText(globalPos, spot->clickActionToolTip()); - if(!_ctrlDrag && ev->modifiers() & Qt::ControlModifier) { - setCursor(QCursor(Qt::PointingHandCursor)); - } else { - setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); - } + update(_mouseOverHotspotArea | previousHotspotArea); + if (_mouseOverHotspotArea.contains(ev->pos())) { + if (spot && spot->type() == Filter::HotSpot::Link && + spot->hasClickAction()) { + QPoint globalPos = mapToGlobal(ev->pos()); + QToolTip::showText(globalPos, spot->clickActionToolTip()); + if (!_ctrlDrag && ev->modifiers() & Qt::ControlModifier) { + setCursor(QCursor(Qt::PointingHandCursor)); + } else { + setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); + } + } else { + setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); + } } else { - setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); + QToolTip::hideText(); + setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); } - } else { - QToolTip::hideText(); - setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); - } - } - else if ( !_mouseOverHotspotArea.isEmpty() ) - { - update( _mouseOverHotspotArea ); + } else if (!_mouseOverHotspotArea.isEmpty()) { + update(_mouseOverHotspotArea); // set hotspot area to an invalid rectangle _mouseOverHotspotArea = QRegion(); QToolTip::hideText(); setCursor(QCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor)); - } - - // for auto-hiding the cursor, we need mouseTracking - if (ev->buttons() == Qt::NoButton ) return; - - // if the terminal is interested in mouse movements - // then emit a mouse movement signal, unless the shift - // key is being held down, which overrides this. - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) - { - int button = 3; - if (ev->buttons() & Qt::LeftButton) - button = 0; - if (ev->buttons() & Qt::MiddleButton) - button = 1; - if (ev->buttons() & Qt::RightButton) - button = 2; + } + // for auto-hiding the cursor, we need mouseTracking + if (ev->buttons() == Qt::NoButton) + return; - emit mouseSignal( button, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), - 1 ); + // if the terminal is interested in mouse movements + // then emit a mouse movement signal, unless the shift + // key is being held down, which overrides this. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { + int button = 3; + if (ev->buttons() & Qt::LeftButton) + button = 0; + if (ev->buttons() & Qt::MiddleButton) + button = 1; + if (ev->buttons() & Qt::RightButton) + button = 2; + + emit mouseSignal(button, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), + 1); - return; - } + return; + } - if (dragInfo.state == diPending) - { - // we had a mouse down, but haven't confirmed a drag yet - // if the mouse has moved sufficiently, we will confirm + if (dragInfo.state == diPending) { + // we had a mouse down, but haven't confirmed a drag yet + // if the mouse has moved sufficiently, we will confirm -// int distance = KGlobalSettings::dndEventDelay(); - int distance = QApplication::startDragDistance(); - if ( ev->position().x() > dragInfo.start.x() + distance || ev->position().x() < dragInfo.start.x() - distance || - ev->position().y() > dragInfo.start.y() + distance || ev->position().y() < dragInfo.start.y() - distance) - { - // we've left the drag square, we can start a real drag operation now - emit isBusySelecting(false); // Ok.. we can breath again. + // int distance = KGlobalSettings::dndEventDelay(); + int distance = QApplication::startDragDistance(); + if (ev->position().x() > dragInfo.start.x() + distance || + ev->position().x() < dragInfo.start.x() - distance || + ev->position().y() > dragInfo.start.y() + distance || + ev->position().y() < dragInfo.start.y() - distance) { + // we've left the drag square, we can start a real drag operation now + emit isBusySelecting(false); // Ok.. we can breath again. - _screenWindow->clearSelection(); - doDrag(); + _screenWindow->clearSelection(); + doDrag(); + } + return; + } else if (dragInfo.state == diDragging) { + // this isn't technically needed because mouseMoveEvent is suppressed during + // Qt drag operations, replaced by dragMoveEvent + return; } - return; - } - else if (dragInfo.state == diDragging) - { - // this isn't technically needed because mouseMoveEvent is suppressed during - // Qt drag operations, replaced by dragMoveEvent - return; - } - if (_actSel == 0) return; + if (_actSel == 0) + return; - // don't extend selection while pasting - if (ev->buttons() & Qt::MiddleButton) return; + // don't extend selection while pasting + if (ev->buttons() & Qt::MiddleButton) + return; - extendSelection( ev->pos() ); + extendSelection(ev->pos()); } -void TerminalDisplay::extendSelection( const QPoint& position ) -{ - QPoint pos = position; - - if ( !_screenWindow ) - return; - - //if ( !contentsRect().contains(ev->pos()) ) return; - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); - int scroll = _scrollBar->value(); - - // we're in the process of moving the mouse with the left button pressed - // the mouse cursor will kept caught within the bounds of the text in - // this widget. - - int linesBeyondWidget = 0; - - QRect textBounds(tLx + _leftMargin, - tLy + _topMargin, - _usedColumns*_fontWidth-1, - _usedLines*_fontHeight-1); - - // Adjust position within text area bounds. - QPoint oldpos = pos; - - pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); - pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); - - if ( oldpos.y() > textBounds.bottom() ) - { - linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; - _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward - } - if ( oldpos.y() < textBounds.top() ) - { - linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight; - _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history - } - - int charColumn = 0; - int charLine = 0; - getCharacterPosition(pos,charLine,charColumn); - - QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); - QPoint ohere; - QPoint _iPntSelCorr = _iPntSel; - _iPntSelCorr.ry() -= _scrollBar->value(); - QPoint _pntSelCorr = _pntSel; - _pntSelCorr.ry() -= _scrollBar->value(); - bool swapping = false; - - if ( _wordSelectionMode ) - { - // Extend to word boundaries - int i; - QChar selClass; - - bool left_not_right = ( here.y() < _iPntSelCorr.y() || - ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); - bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); - swapping = left_not_right != old_left_not_right; - - // Find left (left_not_right ? from here : from start) - QPoint left = left_not_right ? here : _iPntSelCorr; - i = loc(left.x(),left.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(QChar(static_cast(_image[i].character))); - while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) - && charClass(QChar(static_cast(_image[i-1].character))) == selClass ) - { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} } - } - - // Find left (left_not_right ? from start : from here) - QPoint right = left_not_right ? _iPntSelCorr : here; - i = loc(right.x(),right.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(QChar(static_cast(_image[i].character))); - while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) - && charClass(QChar(static_cast(_image[i+1].character))) == selClass ) - { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } } - } - - // Pick which is start (ohere) and which is extension (here) - if ( left_not_right ) - { - here = left; ohere = right; - } - else - { - here = right; ohere = left; - } - ohere.rx()++; - } - - if ( _lineSelectionMode ) - { - // Extend to complete line - bool above_not_below = ( here.y() < _iPntSelCorr.y() ); +void TerminalDisplay::extendSelection(const QPoint &position) { + QPoint pos = position; - QPoint above = above_not_below ? here : _iPntSelCorr; - QPoint below = above_not_below ? _iPntSelCorr : here; + if (!_screenWindow) + return; - while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) ) - above.ry()--; - while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) ) - below.ry()++; + // if ( !contentsRect().contains(ev->pos()) ) return; + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + int scroll = _scrollBar->value(); + + // we're in the process of moving the mouse with the left button pressed + // the mouse cursor will kept caught within the bounds of the text in + // this widget. + + int linesBeyondWidget = 0; + + QRect textBounds(tLx + _leftMargin, tLy + _topMargin, + _usedColumns * _fontWidth - 1, _usedLines * _fontHeight - 1); + + // Adjust position within text area bounds. + QPoint oldpos = pos; + + pos.setX(qBound(textBounds.left(), pos.x(), textBounds.right())); + pos.setY(qBound(textBounds.top(), pos.y(), textBounds.bottom())); + + if (oldpos.y() > textBounds.bottom()) { + linesBeyondWidget = (oldpos.y() - textBounds.bottom()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value() + linesBeyondWidget + + 1); // scrollforward + } + if (oldpos.y() < textBounds.top()) { + linesBeyondWidget = (textBounds.top() - oldpos.y()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value() - linesBeyondWidget - + 1); // history + } + + int charColumn = 0; + int charLine = 0; + getCharacterPosition(pos, charLine, charColumn); + + QPoint here = QPoint( + charColumn, + charLine); // QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); + QPoint ohere; + QPoint _iPntSelCorr = _iPntSel; + _iPntSelCorr.ry() -= _scrollBar->value(); + QPoint _pntSelCorr = _pntSel; + _pntSelCorr.ry() -= _scrollBar->value(); + bool swapping = false; + + if (_wordSelectionMode) { + // Extend to word boundaries + int i; + QChar selClass; + + bool left_not_right = + (here.y() < _iPntSelCorr.y() || + (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x())); + bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() || + (_pntSelCorr.y() == _iPntSelCorr.y() && + _pntSelCorr.x() < _iPntSelCorr.x())); + swapping = left_not_right != old_left_not_right; + + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + i = loc(left.x(), left.y()); + if (i >= 0 && i <= _imageSize) { + selClass = charClass(QChar(static_cast(_image[i].character))); + while ( + ((left.x() > 0) || + (left.y() > 0 && (_lineProperties[left.y() - 1] & LINE_WRAPPED))) && + charClass(QChar(static_cast(_image[i - 1].character))) == + selClass) { + i--; + if (left.x() > 0) + left.rx()--; + else { + left.rx() = _usedColumns - 1; + left.ry()--; + } + } + } - above.setX(0); - below.setX(_usedColumns-1); + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + i = loc(right.x(), right.y()); + if (i >= 0 && i <= _imageSize) { + selClass = charClass(QChar(static_cast(_image[i].character))); + while (((right.x() < _usedColumns - 1) || + (right.y() < _usedLines - 1 && + (_lineProperties[right.y()] & LINE_WRAPPED))) && + charClass(QChar(static_cast(_image[i + 1].character))) == + selClass) { + i++; + if (right.x() < _usedColumns - 1) + right.rx()++; + else { + right.rx() = 0; + right.ry()++; + } + } + } - // Pick which is start (ohere) and which is extension (here) - if ( above_not_below ) - { - here = above; ohere = below; - } - else - { - here = below; ohere = above; + // Pick which is start (ohere) and which is extension (here) + if (left_not_right) { + here = left; + ohere = right; + } else { + here = right; + ohere = left; + } + ohere.rx()++; } - QPoint newSelBegin = QPoint( ohere.x(), ohere.y() ); - swapping = !(_tripleSelBegin==newSelBegin); - _tripleSelBegin = newSelBegin; + if (_lineSelectionMode) { + // Extend to complete line + bool above_not_below = (here.y() < _iPntSelCorr.y()); - ohere.rx()++; - } + QPoint above = above_not_below ? here : _iPntSelCorr; + QPoint below = above_not_below ? _iPntSelCorr : here; - int offset = 0; - if ( !_wordSelectionMode && !_lineSelectionMode ) - { - int i; - QChar selClass; + while (above.y() > 0 && (_lineProperties[above.y() - 1] & LINE_WRAPPED)) + above.ry()--; + while (below.y() < _usedLines - 1 && + (_lineProperties[below.y()] & LINE_WRAPPED)) + below.ry()++; - bool left_not_right = ( here.y() < _iPntSelCorr.y() || - ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); - bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); - swapping = left_not_right != old_left_not_right; + above.setX(0); + below.setX(_usedColumns - 1); - // Find left (left_not_right ? from here : from start) - QPoint left = left_not_right ? here : _iPntSelCorr; + // Pick which is start (ohere) and which is extension (here) + if (above_not_below) { + here = above; + ohere = below; + } else { + here = below; + ohere = above; + } - // Find left (left_not_right ? from start : from here) - QPoint right = left_not_right ? _iPntSelCorr : here; - if ( right.x() > 0 && !_columnSelectionMode ) - { - i = loc(right.x(),right.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(QChar(static_cast(_image[i-1].character))); - /* if (selClass == ' ') - { - while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && - !(_lineProperties[right.y()] & LINE_WRAPPED)) - { i++; right.rx()++; } - if (right.x() < _usedColumns-1) - right = left_not_right ? _iPntSelCorr : here; - else - right.rx()++; // will be balanced later because of offset=-1; - }*/ - } - } - - // Pick which is start (ohere) and which is extension (here) - if ( left_not_right ) - { - here = left; ohere = right; offset = 0; - } - else - { - here = right; ohere = left; offset = -1; + QPoint newSelBegin = QPoint(ohere.x(), ohere.y()); + swapping = !(_tripleSelBegin == newSelBegin); + _tripleSelBegin = newSelBegin; + + ohere.rx()++; + } + + int offset = 0; + if (!_wordSelectionMode && !_lineSelectionMode) { + int i; + QChar selClass; + + bool left_not_right = + (here.y() < _iPntSelCorr.y() || + (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x())); + bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() || + (_pntSelCorr.y() == _iPntSelCorr.y() && + _pntSelCorr.x() < _iPntSelCorr.x())); + swapping = left_not_right != old_left_not_right; + + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + if (right.x() > 0 && !_columnSelectionMode) { + i = loc(right.x(), right.y()); + if (i >= 0 && i <= _imageSize) { + selClass = + charClass(QChar(static_cast(_image[i - 1].character))); + /* if (selClass == ' ') + { + while ( right.x() < _usedColumns-1 && + charClass(_image[i+1].character) == selClass && + (right.y()<_usedLines-1) && + !(_lineProperties[right.y()] & LINE_WRAPPED)) + { i++; right.rx()++; } + if (right.x() < _usedColumns-1) + right = left_not_right ? _iPntSelCorr : here; + else + right.rx()++; // will be balanced later because of offset=-1; + }*/ + } + } + + // Pick which is start (ohere) and which is extension (here) + if (left_not_right) { + here = left; + ohere = right; + offset = 0; + } else { + here = right; + ohere = left; + offset = -1; + } } - } - if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved + if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) + return; // not moved - if (here == ohere) return; // It's not left, it's not right. + if (here == ohere) + return; // It's not left, it's not right. - if ( _actSel < 2 || swapping ) - { - if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) - { - _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true ); - } - else - { - _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false ); + if (_actSel < 2 || swapping) { + if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { + _screenWindow->setSelectionStart(ohere.x(), ohere.y(), true); + } else { + _screenWindow->setSelectionStart(ohere.x() - 1 - offset, ohere.y(), false); + } } - } - _actSel = 2; // within selection - _pntSel = here; - _pntSel.ry() += _scrollBar->value(); + _actSel = 2; // within selection + _pntSel = here; + _pntSel.ry() += _scrollBar->value(); - if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) - { - _screenWindow->setSelectionEnd( here.x() , here.y() ); - } - else - { - _screenWindow->setSelectionEnd( here.x()+offset , here.y() ); - } + if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { + _screenWindow->setSelectionEnd(here.x(), here.y()); + } else { + _screenWindow->setSelectionEnd(here.x() + offset, here.y()); + } } -void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) -{ - if ( !_screenWindow ) +void TerminalDisplay::mouseReleaseEvent(QMouseEvent *ev) { + if (!_screenWindow) return; int charLine; int charColumn; - getCharacterPosition(ev->pos(),charLine,charColumn); + getCharacterPosition(ev->pos(), charLine, charColumn); - if ( ev->button() == Qt::LeftButton) - { - emit isBusySelecting(false); - if(dragInfo.state == diPending) - { - // We had a drag event pending but never confirmed. Kill selection - _screenWindow->clearSelection(); - //emit clearSelectionSignal(); - } - else - { - if ( _actSel > 1 ) - { - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); - } + if (ev->button() == Qt::LeftButton) { + emit isBusySelecting(false); + if (dragInfo.state == diPending) { + // We had a drag event pending but never confirmed. Kill selection + _screenWindow->clearSelection(); + // emit clearSelectionSignal(); + } else { + if (_actSel > 1) { + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + } - _actSel = 0; + _actSel = 0; - //FIXME: emits a release event even if the mouse is - // outside the range. The procedure used in `mouseMoveEvent' - // applies here, too. + // FIXME: emits a release event even if the mouse is + // outside the range. The procedure used in `mouseMoveEvent' + // applies here, too. - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) - emit mouseSignal( 0, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 2); + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + emit mouseSignal( + 0, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 2); + } + dragInfo.state = diNone; } - dragInfo.state = diNone; - } - - if ( !_mouseMarks && - ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) - || ev->button() == Qt::MiddleButton) ) - { - emit mouseSignal( ev->button() == Qt::MiddleButton ? 1 : 2, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , - 2); - } + if (!_mouseMarks && ((ev->button() == Qt::RightButton && + !(ev->modifiers() & Qt::ShiftModifier)) || + ev->button() == Qt::MiddleButton)) { + emit mouseSignal(ev->button() == Qt::MiddleButton ? 1 : 2, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), + 2); + } } -void TerminalDisplay::getCharacterPosition(const QPointF& widgetPoint,int& line,int& column) const -{ - line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight; +void TerminalDisplay::getCharacterPosition(const QPointF &widgetPoint, + int &line, int &column) const { + line = (widgetPoint.y() - contentsRect().top() - _topMargin) / _fontHeight; if (line < 0) line = 0; if (line >= _usedLines) line = _usedLines - 1; - int x = widgetPoint.x() + _fontWidth / 2 - contentsRect().left() - _leftMargin; - if ( _fixedFont ) + int x = + widgetPoint.x() + _fontWidth / 2 - contentsRect().left() - _leftMargin; + if (_fixedFont) column = x / _fontWidth; - else - { + else { column = 0; - while(column + 1 < _usedColumns && x > textWidth(0, column + 1, line)) + while (column + 1 < _usedColumns && x > textWidth(0, column + 1, line)) column++; } - if ( column < 0 ) + if (column < 0) column = 0; // the column value returned can be equal to _usedColumns, which @@ -2753,428 +2671,371 @@ void TerminalDisplay::getCharacterPosition(const QPointF& widgetPoint,int& line, // // this is required so that the user can select characters in the right-most // column (or left-most for right-to-left input) - if ( column > _usedColumns ) + if (column > _usedColumns) column = _usedColumns; } -void TerminalDisplay::updateFilters() -{ - if ( !_screenWindow ) +void TerminalDisplay::updateFilters() { + if (!_screenWindow) return; processFilters(); } -void TerminalDisplay::updateLineProperties() -{ - if ( !_screenWindow ) +void TerminalDisplay::updateLineProperties() { + if (!_screenWindow) return; _lineProperties = _screenWindow->getLineProperties(); } -void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) -{ - if ( ev->button() != Qt::LeftButton) return; - if ( !_screenWindow ) return; - - int charLine = 0; - int charColumn = 0; - - getCharacterPosition(ev->pos(),charLine,charColumn); - - QPoint pos(charColumn,charLine); - - // pass on double click as two clicks. - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) - { - // Send just _ONE_ click event, since the first click of the double click - // was already sent by the click handler - emit mouseSignal( 0, - pos.x()+1, - pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), - 0 ); // left button - return; - } - - _screenWindow->clearSelection(); - QPoint bgnSel = pos; - QPoint endSel = pos; - int i = loc(bgnSel.x(),bgnSel.y()); - _iPntSel = bgnSel; - _iPntSel.ry() += _scrollBar->value(); - - _wordSelectionMode = true; - - // find word boundaries... - QChar selClass = charClass(QChar(static_cast(_image[i].character))); - { - // find the start of the word - int x = bgnSel.x(); - while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) - && charClass(QChar(static_cast(_image[i-1].character))) == selClass ) - { - i--; - if (x>0) - x--; - else - { - x=_usedColumns-1; - bgnSel.ry()--; - } - } - - bgnSel.setX(x); - _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false ); - - // find the end of the word - i = loc( endSel.x(), endSel.y() ); - x = endSel.x(); - while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) - && charClass(QChar(static_cast(_image[i+1].character))) == selClass ) - { - i++; - if (x<_usedColumns-1) - x++; - else - { - x=0; - endSel.ry()++; - } - } - - endSel.setX(x); - - // In word selection mode don't select @ (64) if at end of word. - if ( ( QChar( _image[i].character ) == QLatin1Char('@') ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) - endSel.setX( x - 1 ); - - - _actSel = 2; // within selection - - _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); - - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); - } - - _possibleTripleClick=true; - - QTimer::singleShot(QApplication::doubleClickInterval(),this, - &TerminalDisplay::tripleClickTimeout); -} - -void TerminalDisplay::wheelEvent( QWheelEvent* ev ) -{ - if (ev->angleDelta().y() == 0) +void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent *ev) { + if (ev->button() != Qt::LeftButton) + return; + if (!_screenWindow) return; - if (_mouseMarks && _scrollBar->maximum() > 0) + int charLine = 0; + int charColumn = 0; + + getCharacterPosition(ev->pos(), charLine, charColumn); + + QPoint pos(charColumn, charLine); + + // pass on double click as two clicks. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { + // Send just _ONE_ click event, since the first click of the double click + // was already sent by the click handler + emit mouseSignal(0, pos.x() + 1,pos.y() + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); // left button + return; + } + + _screenWindow->clearSelection(); + QPoint bgnSel = pos; + QPoint endSel = pos; + int i = loc(bgnSel.x(), bgnSel.y()); + _iPntSel = bgnSel; + _iPntSel.ry() += _scrollBar->value(); + + _wordSelectionMode = true; + + // find word boundaries... + QChar selClass = charClass(QChar(static_cast(_image[i].character))); { + // find the start of the word + int x = bgnSel.x(); + while (((x > 0) || (bgnSel.y() > 0 && (_lineProperties[bgnSel.y() - 1] & LINE_WRAPPED))) && + charClass(QChar(static_cast(_image[i - 1].character))) == selClass) { + i--; + if (x > 0) + x--; + else { + x = _usedColumns - 1; + bgnSel.ry()--; + } + } + + bgnSel.setX(x); + _screenWindow->setSelectionStart(bgnSel.x(), bgnSel.y(), false); + + // find the end of the word + i = loc(endSel.x(), endSel.y()); + x = endSel.x(); + while (((x < _usedColumns - 1) || + (endSel.y() < _usedLines - 1 && + (_lineProperties[endSel.y()] & LINE_WRAPPED))) && + charClass(QChar(static_cast(_image[i + 1].character))) == selClass) { + i++; + if (x < _usedColumns - 1) + x++; + else { + x = 0; + endSel.ry()++; + } + } + + endSel.setX(x); + + // In word selection mode don't select @ (64) if at end of word. + if ((QChar(_image[i].character) == QLatin1Char('@')) && ((endSel.x() - bgnSel.x()) > 0)) + endSel.setX(x - 1); + + _actSel = 2; // within selection + + _screenWindow->setSelectionEnd(endSel.x(), endSel.y()); + + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + } + + _possibleTripleClick = true; + + QTimer::singleShot(QApplication::doubleClickInterval(), this, &TerminalDisplay::tripleClickTimeout); +} + +void TerminalDisplay::wheelEvent(QWheelEvent *ev) { + if (ev->angleDelta().y() == 0) + return; + + if (_mouseMarks && _scrollBar->maximum() > 0) { // If the program running in the terminal is not interested in // Mouse events, send the event to the scrollbar if the slider // has room to move _scrollBar->event(ev); - } else if(_mouseMarks && !_isPrimaryScreen) { + } else if (_mouseMarks && !_isPrimaryScreen) { // assume that each Up / Down key event will cause the terminal application // to scroll by one line. // - // to get a reasonable scrolling speed, scroll by one line for every 5 degrees - // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, - // giving a scroll of 3 lines + // to get a reasonable scrolling speed, scroll by one line for every 5 + // degrees of mouse wheel rotation. Mouse wheels typically move in steps of + // 15 degrees, giving a scroll of 3 lines int key = ev->angleDelta().y() > 0 ? Qt::Key_Up : Qt::Key_Down; // QWheelEvent::angleDelta().y() gives rotation in eighths of a degree int wheelDegrees = ev->angleDelta().y() / 8; int linesToScroll = abs(wheelDegrees) / 5; - QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier); + QKeyEvent keyScrollEvent(QEvent::KeyPress, key, Qt::NoModifier); - for (int i=0;iposition() , charLine , charColumn ); + getCharacterPosition(ev->position(), charLine, charColumn); - emit mouseSignal( ev->angleDelta().y() > 0 ? 4 : 5, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , - 0); + emit mouseSignal(ev->angleDelta().y() > 0 ? 4 : 5, charColumn + 1, + charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } } -void TerminalDisplay::tripleClickTimeout() -{ - _possibleTripleClick=false; -} - -void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) -{ - if ( !_screenWindow ) return; - - int charLine; - int charColumn; - getCharacterPosition(ev->pos(),charLine,charColumn); - _iPntSel = QPoint(charColumn,charLine); +void TerminalDisplay::tripleClickTimeout() { _possibleTripleClick = false; } - _screenWindow->clearSelection(); +void TerminalDisplay::mouseTripleClickEvent(QMouseEvent *ev) { + if (!_screenWindow) + return; - _lineSelectionMode = true; - _wordSelectionMode = false; + int charLine; + int charColumn; + getCharacterPosition(ev->pos(), charLine, charColumn); + _iPntSel = QPoint(charColumn, charLine); - _actSel = 2; // within selection - emit isBusySelecting(true); // Keep it steady... + _screenWindow->clearSelection(); - while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - _iPntSel.ry()--; + _lineSelectionMode = true; + _wordSelectionMode = false; - if (_tripleClickMode == SelectForwardsFromCursor) { - // find word boundary start - int i = loc(_iPntSel.x(),_iPntSel.y()); - QChar selClass = charClass(QChar(static_cast(_image[i].character))); - int x = _iPntSel.x(); + _actSel = 2; // within selection + emit isBusySelecting(true); // Keep it steady... - while ( ((x>0) || - (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - ) - && charClass(QChar(static_cast(_image[i-1].character))) == selClass ) - { - i--; - if (x>0) - x--; - else - { - x=_columns-1; - _iPntSel.ry()--; + while (_iPntSel.y() > 0 && (_lineProperties[_iPntSel.y() - 1] & LINE_WRAPPED)) + _iPntSel.ry()--; + + if (_tripleClickMode == SelectForwardsFromCursor) { + // find word boundary start + int i = loc(_iPntSel.x(), _iPntSel.y()); + QChar selClass = charClass(QChar(static_cast(_image[i].character))); + int x = _iPntSel.x(); + + while (((x > 0) || (_iPntSel.y() > 0 && + (_lineProperties[_iPntSel.y() - 1] & LINE_WRAPPED))) && + charClass(QChar(static_cast(_image[i - 1].character))) == selClass) { + i--; + if (x > 0) + x--; + else { + x = _columns - 1; + _iPntSel.ry()--; + } } - } - _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); - _tripleSelBegin = QPoint( x, _iPntSel.y() ); - } - else if (_tripleClickMode == SelectWholeLine) { - _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false ); - _tripleSelBegin = QPoint( 0, _iPntSel.y() ); - } + _screenWindow->setSelectionStart(x, _iPntSel.y(), false); + _tripleSelBegin = QPoint(x, _iPntSel.y()); + } else if (_tripleClickMode == SelectWholeLine) { + _screenWindow->setSelectionStart(0, _iPntSel.y(), false); + _tripleSelBegin = QPoint(0, _iPntSel.y()); + } - while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) - _iPntSel.ry()++; + while (_iPntSel.y() < _lines - 1 && + (_lineProperties[_iPntSel.y()] & LINE_WRAPPED)) + _iPntSel.ry()++; - _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); + _screenWindow->setSelectionEnd(_columns - 1, _iPntSel.y()); - setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); - _iPntSel.ry() += _scrollBar->value(); + _iPntSel.ry() += _scrollBar->value(); } - -bool TerminalDisplay::focusNextPrevChild( bool next ) -{ - if (next) - return false; // This disables changing the active part in konqueror - // when pressing Tab - return QWidget::focusNextPrevChild( next ); +bool TerminalDisplay::focusNextPrevChild(bool next) { + if (next) + return false; // This disables changing the active part in konqueror + // when pressing Tab + return QWidget::focusNextPrevChild(next); } -QChar TerminalDisplay::charClass(QChar qch) const -{ +QChar TerminalDisplay::charClass(QChar qch) const { // check if the character is a space - if ( qch.isSpace() ) return QLatin1Char(' '); + if (qch.isSpace()) + return QLatin1Char(' '); // check if the character is a letter or a number - if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) + if (qch.isLetterOrNumber() || + _wordCharacters.contains(qch, Qt::CaseInsensitive)) return QLatin1Char('a'); // check if the code point is in the ranges for CJK characters uint32_t cp = qch.unicode(); - if ((cp >= 0x4E00 && cp <= 0x9FFF) || // CJK Unified Ideographs - (cp >= 0x3400 && cp <= 0x4DBF) || // CJK Unified Ideographs Extension A - (cp >= 0x20000 && cp <= 0x2A6DF) || // CJK Unified Ideographs Extension B - (cp >= 0xF900 && cp <= 0xFAFF) || // CJK Compatibility Ideographs - (cp >= 0x2F800 && cp <= 0x2FA1F) || // CJK Compatibility Ideographs Supplement - (cp == 0x0) //FIXME: if the character is a null character, becase it is CJK character's dummy - ) { + if ((cp >= 0x4E00 && cp <= 0x9FFF) || // CJK Unified Ideographs + (cp >= 0x3400 && cp <= 0x4DBF) || // CJK Unified Ideographs Extension A + (cp >= 0x20000 && cp <= 0x2A6DF) || // CJK Unified Ideographs Extension B + (cp >= 0xF900 && cp <= 0xFAFF) || // CJK Compatibility Ideographs + (cp >= 0x2F800 && + cp <= 0x2FA1F) || // CJK Compatibility Ideographs Supplement + (cp == 0x0) // FIXME: if the character is a null character, becase it is + // CJK character's dummy + ) { return QLatin1Char('a'); } return qch; } -void TerminalDisplay::setWordCharacters(const QString& wc) -{ +void TerminalDisplay::setWordCharacters(const QString &wc) { _wordCharacters = wc.toLatin1(); } -void TerminalDisplay::setUsesMouse(bool on) -{ +void TerminalDisplay::setUsesMouse(bool on) { if (_mouseMarks != on) { _mouseMarks = on; - setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + setCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor); emit usesMouseChanged(); } } -bool TerminalDisplay::usesMouse() const -{ - return _mouseMarks; -} +bool TerminalDisplay::usesMouse() const { return _mouseMarks; } -void TerminalDisplay::usingPrimaryScreen(bool use) -{ - _isPrimaryScreen = use; -} +void TerminalDisplay::usingPrimaryScreen(bool use) { _isPrimaryScreen = use; } -void TerminalDisplay::setBracketedPasteMode(bool on) -{ +void TerminalDisplay::setBracketedPasteMode(bool on) { _bracketedPasteMode = on; } -bool TerminalDisplay::bracketedPasteMode() const -{ - return _bracketedPasteMode; -} - -/* ------------------------------------------------------------------------- */ -/* */ -/* Clipboard */ -/* */ -/* ------------------------------------------------------------------------- */ +bool TerminalDisplay::bracketedPasteMode() const { return _bracketedPasteMode; } #undef KeyPress -void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) -{ - if ( !_screenWindow ) - return; +void TerminalDisplay::emitSelection(bool useXselection, bool appendReturn) { + if (!_screenWindow) + return; - // Paste Clipboard by simulating keypress events - QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : - QClipboard::Clipboard); - if ( ! text.isEmpty() ) - { - text.replace(QLatin1String("\r\n"), QLatin1String("\n")); - text.replace(QLatin1Char('\n'), QLatin1Char('\r')); + // Paste Clipboard by simulating keypress events + QString text = QApplication::clipboard()->text( + useXselection ? QClipboard::Selection : QClipboard::Clipboard); + if (!text.isEmpty()) { + text.replace(QLatin1String("\r\n"), QLatin1String("\n")); + text.replace(QLatin1Char('\n'), QLatin1Char('\r')); - if (_trimPastedTrailingNewlines) { - text.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); - } + if (_trimPastedTrailingNewlines) { + text.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); + } - if (_confirmMultilinePaste && text.contains(QLatin1Char('\r'))) { - if (!multilineConfirmation(text)) { - return; + if (_confirmMultilinePaste && text.contains(QLatin1Char('\r'))) { + if (!multilineConfirmation(text)) { + return; + } } - } - bracketText(text); + bracketText(text); - // appendReturn is intentionally handled _after_ enclosing texts with brackets as - // that feature is used to allow execution of commands immediately after paste. - // Ref: https://bugs.kde.org/show_bug.cgi?id=16179 - // Ref: https://github.com/KDE/konsole/commit/83d365f2ebfe2e659c1e857a2f5f247c556ab571 - if(appendReturn) { - text.append(QLatin1Char('\r')); - } + // appendReturn is intentionally handled _after_ enclosing texts with + // brackets as that feature is used to allow execution of commands + // immediately after paste. Ref: https://bugs.kde.org/show_bug.cgi?id=16179 + // Ref: + // https://github.com/KDE/konsole/commit/83d365f2ebfe2e659c1e857a2f5f247c556ab571 + if (appendReturn) { + text.append(QLatin1Char('\r')); + } - QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); - emit keyPressedSignal(&e, true); // expose as a big fat keypress event + QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); + emit keyPressedSignal(&e, true); // expose as a big fat keypress event - _screenWindow->clearSelection(); + _screenWindow->clearSelection(); - switch(mMotionAfterPasting) - { - case MoveStartScreenWindow: - // Temporarily stop tracking output, or pasting contents triggers - // ScreenWindow::notifyOutputChanged() and the latter scrolls the - // terminal to the last line. It will be re-enabled when needed - // (e.g., scrolling to the last line). - _screenWindow->setTrackOutput(false); - _screenWindow->scrollTo(0); - break; - case MoveEndScreenWindow: - scrollToEnd(); - break; - case NoMoveScreenWindow: - break; + switch (mMotionAfterPasting) { + case MoveStartScreenWindow: + // Temporarily stop tracking output, or pasting contents triggers + // ScreenWindow::notifyOutputChanged() and the latter scrolls the + // terminal to the last line. It will be re-enabled when needed + // (e.g., scrolling to the last line). + _screenWindow->setTrackOutput(false); + _screenWindow->scrollTo(0); + break; + case MoveEndScreenWindow: + scrollToEnd(); + break; + case NoMoveScreenWindow: + break; + } } - } } -void TerminalDisplay::bracketText(QString& text) const -{ - if (bracketedPasteMode() && !_disabledBracketedPasteMode) - { +void TerminalDisplay::bracketText(QString &text) const { + if (bracketedPasteMode() && !_disabledBracketedPasteMode) { text.prepend(QLatin1String("\033[200~")); text.append(QLatin1String("\033[201~")); } } -bool TerminalDisplay::multilineConfirmation(QString& text) -{ +bool TerminalDisplay::multilineConfirmation(QString &text) { MultilineConfirmationMessageBox confirmation(messageParentWidget); confirmation.setWindowTitle(tr("Paste multiline text")); confirmation.setText(tr("Are you sure you want to paste this text?")); confirmation.setDetailedText(text); - if(confirmation.exec() == QDialog::Accepted){ + if (confirmation.exec() == QDialog::Accepted) { text = confirmation.getDetailedText(); return true; } return false; } -void TerminalDisplay::setSelection(const QString& t) -{ - if (QApplication::clipboard()->supportsSelection()) - { +void TerminalDisplay::setSelection(const QString &t) { + if (QApplication::clipboard()->supportsSelection()) { QApplication::clipboard()->setText(t, QClipboard::Selection); } } -void TerminalDisplay::copyClipboard(QClipboard::Mode mode) -{ - if ( !_screenWindow ) - return; +void TerminalDisplay::copyClipboard(QClipboard::Mode mode) { + if (!_screenWindow) + return; - QString text = _screenWindow->selectedText(_preserveLineBreaks); - if (!text.isEmpty()) - QApplication::clipboard()->setText(text,mode); + QString text = _screenWindow->selectedText(_preserveLineBreaks); + if (!text.isEmpty()) + QApplication::clipboard()->setText(text, mode); } -void TerminalDisplay::pasteClipboard() -{ - emitSelection(false,false); -} +void TerminalDisplay::pasteClipboard() { emitSelection(false, false); } -void TerminalDisplay::pasteSelection() -{ - emitSelection(true,false); -} +void TerminalDisplay::pasteSelection() { emitSelection(true, false); } -void TerminalDisplay::selectAll() -{ - if ( !_screenWindow ) - return; +void TerminalDisplay::selectAll() { + if (!_screenWindow) + return; - _screenWindow->clearSelection(); - _screenWindow->setSelectionStart( 0 , 0 , false ); - _screenWindow->setSelectionEnd( _columns - 1 , _lines - 1 ); - setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + _screenWindow->clearSelection(); + _screenWindow->setSelectionStart(0, 0, false); + _screenWindow->setSelectionEnd(_columns - 1, _lines - 1); + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); } void TerminalDisplay::setConfirmMultilinePaste(bool confirmMultilinePaste) { _confirmMultilinePaste = confirmMultilinePaste; } -void TerminalDisplay::setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) { +void TerminalDisplay::setTrimPastedTrailingNewlines( + bool trimPastedTrailingNewlines) { _trimPastedTrailingNewlines = trimPastedTrailingNewlines; } -/* ------------------------------------------------------------------------- */ -/* */ -/* Keyboard */ -/* */ -/* ------------------------------------------------------------------------- */ - -void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) -{ +void TerminalDisplay::setFlowControlWarningEnabled(bool enable) { _flowControlWarningEnabled = enable; // if the dialog is currently visible and the flow control warning has @@ -3183,28 +3044,22 @@ void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) outputSuspended(false); } -void TerminalDisplay::setMotionAfterPasting(MotionAfterPasting action) -{ +void TerminalDisplay::setMotionAfterPasting(MotionAfterPasting action) { mMotionAfterPasting = action; } -int TerminalDisplay::motionAfterPasting() -{ - return mMotionAfterPasting; -} +int TerminalDisplay::motionAfterPasting() { return mMotionAfterPasting; } -void TerminalDisplay::keyPressEvent( QKeyEvent* event ) -{ - _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't - // know where the current selection is. +void TerminalDisplay::keyPressEvent(QKeyEvent *event) { + _actSel = 0; // Key stroke implies a screen update, so TerminalDisplay won't + // know where the current selection is. - if (_hasBlinkingCursor) - { - _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); - if (_cursorBlinking) - blinkCursorEvent(); - else - _cursorBlinking = false; + if (_hasBlinkingCursor) { + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; } emit keyPressedSignal(event, false); @@ -3212,9 +3067,9 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) event->accept(); } -void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) -{ - QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString()); +void TerminalDisplay::inputMethodEvent(QInputMethodEvent *event) { + QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, + event->commitString()); emit keyPressedSignal(&keyEvent, false); _inputMethodData.preeditString = event->preeditString().toStdWString(); @@ -3222,70 +3077,63 @@ void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) event->accept(); } -QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const -{ - const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); - switch ( query ) - { - case Qt::ImCursorRectangle: - return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); - break; - case Qt::ImFont: - return font(); - break; - case Qt::ImCursorPosition: - // return the cursor position within the current line - return cursorPos.x(); - break; - case Qt::ImSurroundingText: - { - // return the text from the current line - QString lineText; - QTextStream stream(&lineText); - PlainTextDecoder decoder; - decoder.begin(&stream); - decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,0); - decoder.end(); - return lineText; - } - break; - case Qt::ImCurrentSelection: - return QString(); - break; - case Qt::ImHints: - return (int)inputMethodHints(); - break; - default: - break; + +QVariant TerminalDisplay::inputMethodQuery(Qt::InputMethodQuery query) const { + const QPoint cursorPos = + _screenWindow ? _screenWindow->cursorPosition() : QPoint(0, 0); + switch (query) { + case Qt::ImCursorRectangle: + return imageToWidget(QRect(cursorPos.x(), cursorPos.y(), 1, 1)); + break; + case Qt::ImFont: + return font(); + break; + case Qt::ImCursorPosition: + // return the cursor position within the current line + return cursorPos.x(); + break; + case Qt::ImSurroundingText: { + // return the text from the current line + QString lineText; + QTextStream stream(&lineText); + PlainTextDecoder decoder; + decoder.begin(&stream); + decoder.decodeLine(&_image[loc(0, cursorPos.y())], _usedColumns, 0); + decoder.end(); + return lineText; + } break; + case Qt::ImCurrentSelection: + return QString(); + break; + case Qt::ImHints: + return (int)inputMethodHints(); + break; + default: + break; } return QVariant(); } -bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) -{ +bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent *keyEvent) { int modifiers = keyEvent->modifiers(); // When a possible shortcut combination is pressed, // emit the overrideShortcutCheck() signal to allow the host // to decide whether the terminal should override it or not. - if (modifiers != Qt::NoModifier) - { + if (modifiers != Qt::NoModifier) { int modifierCount = 0; unsigned int currentModifier = Qt::ShiftModifier; - while (currentModifier <= Qt::KeypadModifier) - { + while (currentModifier <= Qt::KeypadModifier) { if (modifiers & currentModifier) modifierCount++; currentModifier <<= 1; } - if (modifierCount < 2) - { + if (modifierCount < 2) { bool override = false; - emit overrideShortcutCheck(keyEvent,override); - if (override) - { + emit overrideShortcutCheck(keyEvent, override); + if (override) { keyEvent->accept(); return true; } @@ -3295,342 +3143,299 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) // Override any of the following shortcuts because // they are needed by the terminal int keyCode = keyEvent->key() | modifiers; - switch ( keyCode ) - { - // list is taken from the QLineEdit::event() code - case Qt::Key_Tab: - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - case Qt::Key_Escape: + switch (keyCode) { + // list is taken from the QLineEdit::event() code + case Qt::Key_Tab: + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + case Qt::Key_Escape: keyEvent->accept(); return true; } return false; } -bool TerminalDisplay::event(QEvent* event) -{ - bool eventHandled = false; - switch (event->type()) - { +bool TerminalDisplay::event(QEvent *event) { + bool eventHandled = false; + switch (event->type()) { case QEvent::ShortcutOverride: - eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event); + eventHandled = handleShortcutOverrideEvent((QKeyEvent *)event); break; case QEvent::PaletteChange: case QEvent::ApplicationPaletteChange: - _scrollBar->setPalette( QApplication::palette() ); + _scrollBar->setPalette(QApplication::palette()); break; default: break; - } - return eventHandled ? true : QWidget::event(event); + } + return eventHandled ? true : QWidget::event(event); } -void TerminalDisplay::setBellMode(int mode) -{ - _bellMode=mode; -} +void TerminalDisplay::setBellMode(int mode) { _bellMode = mode; } -void TerminalDisplay::enableBell() -{ - _allowBell = true; -} +void TerminalDisplay::enableBell() { _allowBell = true; } -void TerminalDisplay::bell(const QString& message) -{ - if (_bellMode==NoBell) return; - - //limit the rate at which bells can occur - //...mainly for sound effects where rapid bells in sequence - //produce a horrible noise - if ( _allowBell ) - { - _allowBell = false; - QTimer::singleShot(500,this,&TerminalDisplay::enableBell); +void TerminalDisplay::bell(const QString &message) { + if (_bellMode == NoBell) + return; - if (_bellMode==SystemBeepBell) - { - QApplication::beep(); - } - else if (_bellMode==NotifyBell) - { - emit notifyBell(message); - } - else if (_bellMode==VisualBell) - { - swapColorTable(); - QTimer::singleShot(200,this,&TerminalDisplay::swapColorTable); + // limit the rate at which bells can occur + //...mainly for sound effects where rapid bells in sequence + // produce a horrible noise + if (_allowBell) { + _allowBell = false; + QTimer::singleShot(500, this, &TerminalDisplay::enableBell); + + if (_bellMode == SystemBeepBell) { + QApplication::beep(); + } else if (_bellMode == NotifyBell) { + emit notifyBell(message); + } else if (_bellMode == VisualBell) { + swapColorTable(); + QTimer::singleShot(200, this, &TerminalDisplay::swapColorTable); + } } - } } -void TerminalDisplay::selectionChanged() -{ +void TerminalDisplay::selectionChanged() { emit copyAvailable(_screenWindow->selectedText(false).isEmpty() == false); } -void TerminalDisplay::swapColorTable() -{ - ColorEntry color = _colorTable[1]; - _colorTable[1]=_colorTable[0]; - _colorTable[0]= color; - _colorsInverted = !_colorsInverted; - update(); +void TerminalDisplay::swapColorTable() { + ColorEntry color = _colorTable[1]; + _colorTable[1] = _colorTable[0]; + _colorTable[0] = color; + _colorsInverted = !_colorsInverted; + update(); } -void TerminalDisplay::clearImage() -{ - // We initialize _image[_imageSize] too. See makeImage() - for (int i = 0; i <= _imageSize; i++) - { - _image[i].character = ' '; - _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT, - DEFAULT_FORE_COLOR); - _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT, - DEFAULT_BACK_COLOR); - _image[i].rendition = DEFAULT_RENDITION; - } -} - -void TerminalDisplay::calcGeometry() -{ - _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); - int scrollBarWidth = _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) - ? 0 : _scrollBar->width(); - switch(_scrollbarLocation) - { - case QTermWidget::NoScrollBar : - _leftMargin = _leftBaseMargin; - _contentWidth = contentsRect().width() - 2 * _leftBaseMargin; - break; - case QTermWidget::ScrollBarLeft : - _leftMargin = _leftBaseMargin + scrollBarWidth; - _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; - _scrollBar->move(contentsRect().topLeft()); - break; +void TerminalDisplay::clearImage() { + // We initialize _image[_imageSize] too. See makeImage() + for (int i = 0; i <= _imageSize; i++) { + _image[i].character = ' '; + _image[i].foregroundColor = + CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); + _image[i].backgroundColor = + CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); + _image[i].rendition = DEFAULT_RENDITION; + } +} + +void TerminalDisplay::calcGeometry() { + _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); + int scrollBarWidth = _scrollBar->style()->styleHint( + QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) + ? 0 + : _scrollBar->width(); + switch (_scrollbarLocation) { + case QTermWidget::NoScrollBar: + _leftMargin = _leftBaseMargin; + _contentWidth = contentsRect().width() - 2 * _leftBaseMargin; + break; + case QTermWidget::ScrollBarLeft: + _leftMargin = _leftBaseMargin + scrollBarWidth; + _contentWidth = + contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; + _scrollBar->move(contentsRect().topLeft()); + break; case QTermWidget::ScrollBarRight: - _leftMargin = _leftBaseMargin; - _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; - _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1, 0)); - break; - } + _leftMargin = _leftBaseMargin; + _contentWidth = + contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; + _scrollBar->move(contentsRect().topRight() - + QPoint(_scrollBar->width() - 1, 0)); + break; + } - _topMargin = _topBaseMargin; - _contentHeight = contentsRect().height() - 2 * _topBaseMargin + /* mysterious */ 1; + _topMargin = _topBaseMargin; + _contentHeight = + contentsRect().height() - 2 * _topBaseMargin + /* mysterious */ 1; - if (!_isFixedSize) - { - // ensure that display is always at least one column wide - _columns = qMax(1,_contentWidth / _fontWidth); - _usedColumns = qMin(_usedColumns,_columns); + if (!_isFixedSize) { + // ensure that display is always at least one column wide + _columns = qMax(1, _contentWidth / _fontWidth); + _usedColumns = qMin(_usedColumns, _columns); - // ensure that display is always at least one line high - _lines = qMax(1,_contentHeight / _fontHeight); - _usedLines = qMin(_usedLines,_lines); - } + // ensure that display is always at least one line high + _lines = qMax(1, _contentHeight / _fontHeight); + _usedLines = qMin(_usedLines, _lines); + } } -void TerminalDisplay::makeImage() -{ - calcGeometry(); +void TerminalDisplay::makeImage() { + calcGeometry(); - // confirm that array will be of non-zero size, since the painting code - // assumes a non-zero array length - Q_ASSERT( _lines > 0 && _columns > 0 ); - Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); + // confirm that array will be of non-zero size, since the painting code + // assumes a non-zero array length + Q_ASSERT(_lines > 0 && _columns > 0); + Q_ASSERT(_usedLines <= _lines && _usedColumns <= _columns); - _imageSize=_lines*_columns; + _imageSize = _lines * _columns; - // We over-commit one character so that we can be more relaxed in dealing with - // certain boundary conditions: _image[_imageSize] is a valid but unused position - _image = new Character[_imageSize+1]; + // We over-commit one character so that we can be more relaxed in dealing with + // certain boundary conditions: _image[_imageSize] is a valid but unused + // position + _image = new Character[_imageSize + 1]; - clearImage(); + clearImage(); } // calculate the needed size, this must be synced with calcGeometry() -void TerminalDisplay::setSize(int columns, int lines) -{ - int scrollBarWidth = (_scrollBar->isHidden() - || _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) - ? 0 : _scrollBar->sizeHint().width(); - int horizontalMargin = 2 * _leftBaseMargin; - int verticalMargin = 2 * _topBaseMargin; +void TerminalDisplay::setSize(int columns, int lines) { + int scrollBarWidth = + (_scrollBar->isHidden() || + _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? 0 + : _scrollBar->sizeHint().width(); + int horizontalMargin = 2 * _leftBaseMargin; + int verticalMargin = 2 * _topBaseMargin; - QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) , - verticalMargin + (lines * _fontHeight) ); + QSize newSize = + QSize(horizontalMargin + scrollBarWidth + (columns * _fontWidth), + verticalMargin + (lines * _fontHeight)); - if ( newSize != size() ) - { - _size = newSize; - updateGeometry(); - } + if (newSize != size()) { + _size = newSize; + updateGeometry(); + } } -void TerminalDisplay::setFixedSize(int cols, int lins) -{ - _isFixedSize = true; - - //ensure that display is at least one line by one column in size - _columns = qMax(1,cols); - _lines = qMax(1,lins); - _usedColumns = qMin(_usedColumns,_columns); - _usedLines = qMin(_usedLines,_lines); +void TerminalDisplay::setFixedSize(int cols, int lins) { + _isFixedSize = true; - if (_image) - { - delete[] _image; - makeImage(); - } - setSize(cols, lins); - QWidget::setFixedSize(_size); -} + // ensure that display is at least one line by one column in size + _columns = qMax(1, cols); + _lines = qMax(1, lins); + _usedColumns = qMin(_usedColumns, _columns); + _usedLines = qMin(_usedLines, _lines); -QSize TerminalDisplay::sizeHint() const -{ - return _size; + if (_image) { + delete[] _image; + makeImage(); + } + setSize(cols, lins); + QWidget::setFixedSize(_size); } +QSize TerminalDisplay::sizeHint() const { return _size; } -/* --------------------------------------------------------------------- */ -/* */ -/* Drag & Drop */ -/* */ -/* --------------------------------------------------------------------- */ - -void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) -{ - if (event->mimeData()->hasFormat(QLatin1String("text/plain"))) - event->acceptProposedAction(); - if (event->mimeData()->urls().count()) - event->acceptProposedAction(); +void TerminalDisplay::dragEnterEvent(QDragEnterEvent *event) { + if (event->mimeData()->hasFormat(QLatin1String("text/plain"))) + event->acceptProposedAction(); + if (event->mimeData()->urls().count()) + event->acceptProposedAction(); } -void TerminalDisplay::dropEvent(QDropEvent* event) -{ - //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); - QList urls = event->mimeData()->urls(); - - QString dropText; - if (!urls.isEmpty()) - { - // TODO/FIXME: escape or quote pasted things if necessary... - qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please"; - for ( int i = 0 ; i < urls.count() ; i++ ) - { - //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); - QUrl url = urls[i]; +void TerminalDisplay::dropEvent(QDropEvent *event) { + // KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + QList urls = event->mimeData()->urls(); - QString urlText; + QString dropText; + if (!urls.isEmpty()) { + // TODO/FIXME: escape or quote pasted things if necessary... + qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any " + "errors, please"; + for (int i = 0; i < urls.count(); i++) { + // KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); + QUrl url = urls[i]; - if (url.isLocalFile()) - urlText = url.path(); - else - urlText = url.toString(); + QString urlText; - // in future it may be useful to be able to insert file names with drag-and-drop - // without quoting them (this only affects paths with spaces in) - //urlText = KShell::quoteArg(urlText); + if (url.isLocalFile()) + urlText = url.path(); + else + urlText = url.toString(); - QChar q(QLatin1Char('\'')); - dropText += q + QString(urlText).replace(q, QLatin1String("'\\''")) + q; - dropText += QLatin1Char(' '); - } - } - else - { - dropText = event->mimeData()->text(); + // in future it may be useful to be able to insert file names with + // drag-and-drop without quoting them (this only affects paths with spaces + // in) + // urlText = KShell::quoteArg(urlText); - dropText.replace(QLatin1String("\r\n"), QLatin1String("\n")); - dropText.replace(QLatin1Char('\n'), QLatin1Char('\r')); - if (_trimPastedTrailingNewlines) - { - dropText.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); - } - if (_confirmMultilinePaste && dropText.contains(QLatin1Char('\r'))) - { - if (!multilineConfirmation(dropText)) - { - return; - } - } - } - - emit sendStringToEmu(dropText.toLocal8Bit().constData()); -} + QChar q(QLatin1Char('\'')); + dropText += q + QString(urlText).replace(q, QLatin1String("'\\''")) + q; + dropText += QLatin1Char(' '); + } + } else { + dropText = event->mimeData()->text(); -void TerminalDisplay::doDrag() -{ - dragInfo.state = diDragging; - dragInfo.dragObject = new QDrag(this); - QMimeData *mimeData = new QMimeData; - mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); - dragInfo.dragObject->setMimeData(mimeData); - dragInfo.dragObject->exec(Qt::CopyAction); - // Don't delete the QTextDrag object. Qt will delete it when it's done with it. -} + dropText.replace(QLatin1String("\r\n"), QLatin1String("\n")); + dropText.replace(QLatin1Char('\n'), QLatin1Char('\r')); + if (_trimPastedTrailingNewlines) { + dropText.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); + } + if (_confirmMultilinePaste && dropText.contains(QLatin1Char('\r'))) { + if (!multilineConfirmation(dropText)) { + return; + } + } + } -void TerminalDisplay::outputSuspended(bool suspended) -{ - //create the label when this function is first called - if (!_outputSuspendedLabel) - { - //This label includes a link to an English language website - //describing the 'flow control' (Xon/Xoff) feature found in almost - //all terminal emulators. - //If there isn't a suitable article available in the target language the link - //can simply be removed. - _outputSuspendedLabel = new QLabel( tr("Output has been " - "suspended" - " by pressing Ctrl+S." - " Press Ctrl+Q to resume."), - this ); - - QPalette palette(_outputSuspendedLabel->palette()); - //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); - _outputSuspendedLabel->setPalette(palette); - _outputSuspendedLabel->setAutoFillBackground(true); - _outputSuspendedLabel->setBackgroundRole(QPalette::Base); - _outputSuspendedLabel->setFont(QApplication::font()); - _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); - - //enable activation of "Xon/Xoff" link in label - _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | - Qt::LinksAccessibleByKeyboard); - _outputSuspendedLabel->setOpenExternalLinks(true); - _outputSuspendedLabel->setVisible(false); - - _gridLayout->addWidget(_outputSuspendedLabel); - _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, - QSizePolicy::Expanding), - 1,0); + emit sendStringToEmu(dropText.toLocal8Bit().constData()); +} + +void TerminalDisplay::doDrag() { + dragInfo.state = diDragging; + dragInfo.dragObject = new QDrag(this); + QMimeData *mimeData = new QMimeData; + mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); + dragInfo.dragObject->setMimeData(mimeData); + dragInfo.dragObject->exec(Qt::CopyAction); + // Don't delete the QTextDrag object. Qt will delete it when it's done with + // it. +} + +void TerminalDisplay::outputSuspended(bool suspended) { + // create the label when this function is first called + if (!_outputSuspendedLabel) { + // This label includes a link to an English language website + // describing the 'flow control' (Xon/Xoff) feature found in almost + // all terminal emulators. + // If there isn't a suitable article available in the target language the + // link can simply be removed. + _outputSuspendedLabel = new QLabel( + tr("Output has been " + "suspended" + " by pressing Ctrl+S." + " Press Ctrl+Q to resume."), + this); + + QPalette palette(_outputSuspendedLabel->palette()); + // KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); + _outputSuspendedLabel->setPalette(palette); + _outputSuspendedLabel->setAutoFillBackground(true); + _outputSuspendedLabel->setBackgroundRole(QPalette::Base); + _outputSuspendedLabel->setFont(QApplication::font()); + _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); + + // enable activation of "Xon/Xoff" link in label + _outputSuspendedLabel->setTextInteractionFlags( + Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + _outputSuspendedLabel->setOpenExternalLinks(true); + _outputSuspendedLabel->setVisible(false); + + _gridLayout->addWidget(_outputSuspendedLabel); + _gridLayout->addItem( + new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), + 1, 0); } _outputSuspendedLabel->setVisible(suspended); } -uint TerminalDisplay::lineSpacing() const -{ - return _lineSpacing; -} +uint TerminalDisplay::lineSpacing() const { return _lineSpacing; } -void TerminalDisplay::setLineSpacing(uint i) -{ - _lineSpacing = i; - setVTFont(font()); // Trigger an update. +void TerminalDisplay::setLineSpacing(uint i) { + _lineSpacing = i; + setVTFont(font()); // Trigger an update. } -int TerminalDisplay::margin() const -{ - return _topBaseMargin; -} +int TerminalDisplay::margin() const { return _topBaseMargin; } -void TerminalDisplay::setMargin(int i) -{ +void TerminalDisplay::setMargin(int i) { _topBaseMargin = i; _leftBaseMargin = i; } @@ -3644,72 +3449,61 @@ int TerminalDisplay::getCursorY() const { } void TerminalDisplay::setCursorX(int x) { - if(!_screenWindow.isNull()) - _screenWindow->setCursorX(x); + if (!_screenWindow.isNull()) + _screenWindow->setCursorX(x); } void TerminalDisplay::setCursorY(int y) { - if(!_screenWindow.isNull()) - _screenWindow->setCursorY(y); + if (!_screenWindow.isNull()) + _screenWindow->setCursorY(y); } QString TerminalDisplay::screenGet(int row1, int col1, int row2, int col2, int mode) { - return _screenWindow.isNull() ? QString() : _screenWindow->getScreenText(row1, col1, row2, col2, mode); + return _screenWindow.isNull() + ? QString() + : _screenWindow->getScreenText(row1, col1, row2, col2, mode); } -AutoScrollHandler::AutoScrollHandler(QWidget* parent) -: QObject(parent) -, _timerId(0) -{ +AutoScrollHandler::AutoScrollHandler(QWidget *parent) + : QObject(parent), _timerId(0) { parent->installEventFilter(this); } -void AutoScrollHandler::timerEvent(QTimerEvent* event) -{ +void AutoScrollHandler::timerEvent(QTimerEvent *event) { if (event->timerId() != _timerId) return; - QMouseEvent mouseEvent( QEvent::MouseMove, - widget()->mapFromGlobal(QCursor::pos()), - QCursor::pos(), - Qt::NoButton, - Qt::LeftButton, - Qt::NoModifier); + QMouseEvent mouseEvent( + QEvent::MouseMove, widget()->mapFromGlobal(QCursor::pos()), + QCursor::pos(), Qt::NoButton, Qt::LeftButton, Qt::NoModifier); - QApplication::sendEvent(widget(),&mouseEvent); + QApplication::sendEvent(widget(), &mouseEvent); } -bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) -{ - Q_ASSERT( watched == parent() ); - Q_UNUSED( watched ); +bool AutoScrollHandler::eventFilter(QObject *watched, QEvent *event) { + Q_ASSERT(watched == parent()); + Q_UNUSED(watched); - QMouseEvent* mouseEvent = (QMouseEvent*)event; - switch (event->type()) - { - case QEvent::MouseMove: - { - bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); + QMouseEvent *mouseEvent = (QMouseEvent *)event; + switch (event->type()) { + case QEvent::MouseMove: { + bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); - if (mouseInWidget) - { - if (_timerId) - killTimer(_timerId); - _timerId = 0; - } - else - { - if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) - _timerId = startTimer(100); - } - break; - } - case QEvent::MouseButtonRelease: - if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) - { + if (mouseInWidget) { + if (_timerId) killTimer(_timerId); - _timerId = 0; - } + _timerId = 0; + } else { + if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) + _timerId = startTimer(100); + } + break; + } + case QEvent::MouseButtonRelease: + if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) { + killTimer(_timerId); + _timerId = 0; + } break; - default: + default: break; }; diff --git a/lib/qtermwidget/TerminalDisplay.h b/lib/qtermwidget/TerminalDisplay.h index 6a338446..7f7a6052 100644 --- a/lib/qtermwidget/TerminalDisplay.h +++ b/lib/qtermwidget/TerminalDisplay.h @@ -1,21 +1,21 @@ /* - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #ifndef TERMINALDISPLAY_H @@ -75,8 +75,6 @@ enum BackgroundMode { Tile }; -extern unsigned short vt100_graphics[32]; - class ScreenWindow; /** diff --git a/lib/qtermwidget/Vt102Emulation.cpp b/lib/qtermwidget/Vt102Emulation.cpp index 20cd3bb7..e578eda8 100644 --- a/lib/qtermwidget/Vt102Emulation.cpp +++ b/lib/qtermwidget/Vt102Emulation.cpp @@ -1,75 +1,68 @@ /* - This file is part of Konsole, an X terminal. - - Copyright 2007-2008 by Robert Knight - Copyright 1997,1998 by Lars Doelle - - 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; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. + This file is part of Konsole, an X terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ #include "Vt102Emulation.h" #include "tools.h" -#include #include +#include -#include -#include -#include #include +#include +#include #include +#include +#include #include -#include #include "KeyboardTranslator.h" #include "Screen.h" Vt102Emulation::Vt102Emulation() - : Emulation(), - prevCC(0), - _titleUpdateTimer(new QTimer(this)), - _reportFocusEvents(false), - _toUtf8(QStringEncoder::Utf8), - _isTitleChanged(false) -{ - _titleUpdateTimer->setSingleShot(true); - QObject::connect(_titleUpdateTimer, &QTimer::timeout, - this, &Vt102Emulation::updateTitle); - - initTokenizer(); - reset(); + : Emulation(), prevCC(0), _titleUpdateTimer(new QTimer(this)), + _reportFocusEvents(false), _toUtf8(QStringEncoder::Utf8), + _isTitleChanged(false) { + _titleUpdateTimer->setSingleShot(true); + QObject::connect(_titleUpdateTimer, &QTimer::timeout, this, + &Vt102Emulation::updateTitle); + + initTokenizer(); + reset(); } -Vt102Emulation::~Vt102Emulation() -{} +Vt102Emulation::~Vt102Emulation() {} -void Vt102Emulation::clearEntireScreen() -{ - _currentScreen->clearEntireScreen(); - bufferedUpdate(); +void Vt102Emulation::clearEntireScreen() { + _currentScreen->clearEntireScreen(); + bufferedUpdate(); } -void Vt102Emulation::reset() -{ - resetTokenizer(); - resetModes(); - resetCharset(0); - _screen[0]->reset(); - resetCharset(1); - _screen[1]->reset(); - - bufferedUpdate(); +void Vt102Emulation::reset() { + resetTokenizer(); + resetModes(); + resetCharset(0); + _screen[0]->reset(); + resetCharset(1); + _screen[1]->reset(); + + bufferedUpdate(); } /* ------------------------------------------------------------------------- */ @@ -80,73 +73,74 @@ void Vt102Emulation::reset() /* Incoming Bytes Event pipeline - This section deals with decoding the incoming character stream. - Decoding means here, that the stream is first separated into `tokens' - which are then mapped to a `meaning' provided as operations by the - `Screen' class or by the emulation class itself. + This section deals with decoding the incoming character stream. + Decoding means here, that the stream is first separated into `tokens' + which are then mapped to a `meaning' provided as operations by the + `Screen' class or by the emulation class itself. - The pipeline proceeds as follows: + The pipeline proceeds as follows: - - Tokenizing the ESC codes (onReceiveChar) - - VT100 code page translation of plain characters (applyCharset) - - Interpretation of ESC codes (processToken) + - Tokenizing the ESC codes (onReceiveChar) + - VT100 code page translation of plain characters (applyCharset) + - Interpretation of ESC codes (processToken) - The escape codes and their meaning are described in the - technical reference of this program. + The escape codes and their meaning are described in the + technical reference of this program. */ // Tokens ------------------------------------------------------------------ -- /* - Since the tokens are the central notion if this section, we've put them - in front. They provide the syntactical elements used to represent the - terminals operations as byte sequences. - - They are encodes here into a single machine word, so that we can later - switch over them easily. Depending on the token itself, additional - argument variables are filled with parameter values. - - The tokens are defined below: - - - CHR - Printable characters (32..255 but DEL (=127)) - - CTL - Control characters (0..31 but ESC (= 27), DEL) - - ESC - Escape codes of the form - - ESC_DE - Escape codes of the form C - - CSI_PN - Escape codes of the form '[' {Pn} ';' {Pn} C - - CSI_PS - Escape codes of the form '[' {Pn} ';' ... C - - CSI_PS_SP - Escape codes of the form '[' {Pn} ';' ... {Space} C - - CSI_PR - Escape codes of the form '[' '?' {Pn} ';' ... C - - CSI_PE - Escape codes of the form '[' '!' {Pn} ';' ... C - - VT52 - VT52 escape codes - - - - 'Y'{Pc}{Pc} - - XTE_HA - Xterm window/terminal attribute commands - of the form `]' {Pn} `;' {Text} - (Note that these are handled differently to the other formats) - - The last two forms allow list of arguments. Since the elements of - the lists are treated individually the same way, they are passed - as individual tokens to the interpretation. Further, because the - meaning of the parameters are names (although represented as numbers), - they are includes within the token ('N'). + Since the tokens are the central notion if this section, we've put them + in front. They provide the syntactical elements used to represent the + terminals operations as byte sequences. + + They are encodes here into a single machine word, so that we can later + switch over them easily. Depending on the token itself, additional + argument variables are filled with parameter values. + + The tokens are defined below: + + - CHR - Printable characters (32..255 but DEL (=127)) + - CTL - Control characters (0..31 but ESC (= 27), DEL) + - ESC - Escape codes of the form + - ESC_DE - Escape codes of the form C + - CSI_PN - Escape codes of the form '[' {Pn} ';' {Pn} C + - CSI_PS - Escape codes of the form '[' {Pn} ';' ... C + - CSI_PS_SP - Escape codes of the form '[' {Pn} ';' ... {Space} C + - CSI_PR - Escape codes of the form '[' '?' {Pn} ';' ... C + - CSI_PE - Escape codes of the form '[' '!' {Pn} ';' ... C + - VT52 - VT52 escape codes + - + - 'Y'{Pc}{Pc} + - XTE_HA - Xterm window/terminal attribute commands + of the form `]' {Pn} `;' {Text} + (Note that these are handled differently to the other formats) + + The last two forms allow list of arguments. Since the elements of + the lists are treated individually the same way, they are passed + as individual tokens to the interpretation. Further, because the + meaning of the parameters are names (although represented as numbers), + they are includes within the token ('N'). */ -#define TY_CONSTRUCT(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) ) +#define TY_CONSTRUCT(T, A, N) \ + (((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff)) -#define TY_CHR( ) TY_CONSTRUCT(0,0,0) -#define TY_CTL(A ) TY_CONSTRUCT(1,A,0) -#define TY_ESC(A ) TY_CONSTRUCT(2,A,0) -#define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) -#define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) -#define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) -#define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) -#define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) -#define TY_CSI_PS_SP(A,N) TY_CONSTRUCT(11,A,N) +#define TY_CHR() TY_CONSTRUCT(0, 0, 0) +#define TY_CTL(A) TY_CONSTRUCT(1, A, 0) +#define TY_ESC(A) TY_CONSTRUCT(2, A, 0) +#define TY_ESC_CS(A, B) TY_CONSTRUCT(3, A, B) +#define TY_ESC_DE(A) TY_CONSTRUCT(4, A, 0) +#define TY_CSI_PS(A, N) TY_CONSTRUCT(5, A, N) +#define TY_CSI_PN(A) TY_CONSTRUCT(6, A, 0) +#define TY_CSI_PR(A, N) TY_CONSTRUCT(7, A, N) +#define TY_CSI_PS_SP(A, N) TY_CONSTRUCT(11, A, N) -#define TY_VT52(A) TY_CONSTRUCT(8,A,0) -#define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) -#define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) +#define TY_VT52(A) TY_CONSTRUCT(8, A, 0) +#define TY_CSI_PG(A) TY_CONSTRUCT(9, A, 0) +#define TY_CSI_PE(A) TY_CONSTRUCT(10, A, 0) #define MAX_ARGUMENT 4096 @@ -154,231 +148,269 @@ void Vt102Emulation::reset() /* The tokenizer's state - The state is represented by the buffer (tokenBuffer, tokenBufferPos), - and accompanied by decoded arguments kept in (argv,argc). - Note that they are kept internal in the tokenizer. + The state is represented by the buffer (tokenBuffer, tokenBufferPos), + and accompanied by decoded arguments kept in (argv,argc). + Note that they are kept internal in the tokenizer. */ -void Vt102Emulation::resetTokenizer() -{ - tokenBufferPos = 0; - argc = 0; - argv[0] = 0; - argv[1] = 0; - prevCC = 0; +void Vt102Emulation::resetTokenizer() { + tokenBufferPos = 0; + argc = 0; + argv[0] = 0; + argv[1] = 0; + prevCC = 0; } -void Vt102Emulation::addDigit(int digit) -{ - if (argv[argc] < MAX_ARGUMENT) - argv[argc] = 10*argv[argc] + digit; +void Vt102Emulation::addDigit(int digit) { + if (argv[argc] < MAX_ARGUMENT) + argv[argc] = 10 * argv[argc] + digit; } -void Vt102Emulation::addArgument() -{ - argc = qMin(argc+1,MAXARGS-1); - argv[argc] = 0; +void Vt102Emulation::addArgument() { + argc = qMin(argc + 1, MAXARGS - 1); + argv[argc] = 0; } -void Vt102Emulation::addToCurrentToken(wchar_t cc) -{ - tokenBuffer[tokenBufferPos] = cc; - tokenBufferPos = qMin(tokenBufferPos+1,MAX_TOKEN_LENGTH-1); +void Vt102Emulation::addToCurrentToken(wchar_t cc) { + tokenBuffer[tokenBufferPos] = cc; + tokenBufferPos = qMin(tokenBufferPos + 1, MAX_TOKEN_LENGTH - 1); } // Character Class flags used while decoding -#define CTL 1 // Control character -#define CHR 2 // Printable character -#define CPN 4 // TODO: Document me -#define DIG 8 // Digit -#define SCS 16 // TODO: Document me -#define GRP 32 // TODO: Document me -#define CPS 64 // Character which indicates end of window resize - // escape sequence '\e[8;;t' - -void Vt102Emulation::initTokenizer() -{ - int i; - quint8* s; - for(i = 0;i < 256; ++i) - charClass[i] = 0; - for(i = 0;i < 32; ++i) - charClass[i] |= CTL; - for(i = 32;i < 256; ++i) - charClass[i] |= CHR; - for(s = (quint8*)"@ABCDEFGHILMPSTXZbcdfry"; *s; ++s) - charClass[*s] |= CPN; - // resize = \e[8;;t - for(s = (quint8*)"t"; *s; ++s) - charClass[*s] |= CPS; - for(s = (quint8*)"0123456789"; *s; ++s) - charClass[*s] |= DIG; - for(s = (quint8*)"()+*%"; *s; ++s) - charClass[*s] |= SCS; - for(s = (quint8*)"()+*#[]%"; *s; ++s) - charClass[*s] |= GRP; - - resetTokenizer(); +#define CTL 1 // Control character +#define CHR 2 // Printable character +#define CPN 4 // TODO: Document me +#define DIG 8 // Digit +#define SCS 16 // TODO: Document me +#define GRP 32 // TODO: Document me +#define CPS \ + 64 // Character which indicates end of window resize + // escape sequence '\e[8;;t' + +void Vt102Emulation::initTokenizer() { + int i; + quint8 *s; + for (i = 0; i < 256; ++i) + charClass[i] = 0; + for (i = 0; i < 32; ++i) + charClass[i] |= CTL; + for (i = 32; i < 256; ++i) + charClass[i] |= CHR; + for (s = (quint8 *)"@ABCDEFGHILMPSTXZbcdfry"; *s; ++s) + charClass[*s] |= CPN; + // resize = \e[8;;t + for (s = (quint8 *)"t"; *s; ++s) + charClass[*s] |= CPS; + for (s = (quint8 *)"0123456789"; *s; ++s) + charClass[*s] |= DIG; + for (s = (quint8 *)"()+*%"; *s; ++s) + charClass[*s] |= SCS; + for (s = (quint8 *)"()+*#[]%"; *s; ++s) + charClass[*s] |= GRP; + + resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. - Instead of keeping an explicit state, we deduce it from the - token scanned so far. It is then immediately combined with - the current character to form a scanning decision. + Instead of keeping an explicit state, we deduce it from the + token scanned so far. It is then immediately combined with + the current character to form a scanning decision. - This is done by the following defines. + This is done by the following defines. - - P is the length of the token scanned so far. - - L (often P-1) is the position on which contents we base a decision. - - C is a character or a group of characters (taken from 'charClass'). + - P is the length of the token scanned so far. + - L (often P-1) is the position on which contents we base a decision. + - C is a character or a group of characters (taken from 'charClass'). - - 'cc' is the current character - - 's' is a pointer to the start of the token buffer - - 'p' is the current position within the token buffer + - 'cc' is the current character + - 's' is a pointer to the start of the token buffer + - 'p' is the current position within the token buffer - Note that they need to applied in proper order. + Note that they need to applied in proper order. */ -#define lec(P,L,C) (p == (P) && s[(L)] == (C)) -#define lun( ) (p == 1 && cc >= 32 ) -#define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) -#define eec(C) (p >= 3 && cc == (C)) -#define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) -#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) -#define epp( ) (p >= 3 && s[2] == '?') -#define epe( ) (p >= 3 && s[2] == '!') -#define egt( ) (p >= 3 && s[2] == '>') -#define esp( ) (p == 4 && s[3] == ' ') -#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') -#define Xte (Xpe && (cc == 7 || (prevCC == 27 && cc == 92) )) // 27, 92 => "\e\\" (ST, String Terminator) -#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) - -#define CNTL(c) ((c)-'@') +#define lec(P, L, C) (p == (P) && s[(L)] == (C)) +#define lun() (p == 1 && cc >= 32) +#define les(P, L, C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) +#define eec(C) (p >= 3 && cc == (C)) +#define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) +#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) +#define epp() (p >= 3 && s[2] == '?') +#define epe() (p >= 3 && s[2] == '!') +#define egt() (p >= 3 && s[2] == '>') +#define esp() (p == 4 && s[3] == ' ') +#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') +#define Xte (Xpe && (cc == 7 || (prevCC == 27 && cc == 92))) // 27, 92 => "\e\\" (ST, String Terminator) +#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) + +#define CNTL(c) ((c) - '@') #define ESC 27 #define DEL 127 // process an incoming unicode character -void Vt102Emulation::receiveChar(wchar_t cc) -{ - if ((cc == L'\r')||(cc == L'\n')) - dupDisplayCharacter(cc); - if (cc == DEL) - return; //VT100: ignore. - - if (ces(CTL)) - { - // ignore control characters in the text part of Xpe (aka OSC) "ESC]" - // escape sequences; this matches what XTERM docs say - if (Xpe) { - prevCC = cc; - return; - } +void Vt102Emulation::receiveChar(wchar_t cc) { + if ((cc == L'\r') || (cc == L'\n')) + dupDisplayCharacter(cc); + if (cc == DEL) + return; // VT100: ignore. + + if (ces(CTL)) { + // ignore control characters in the text part of Xpe (aka OSC) "ESC]" + // escape sequences; this matches what XTERM docs say + if (Xpe) { + prevCC = cc; + return; + } - // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 - // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do - // of course. Guess this originates from a weakly layered handling of the X-on - // X-off protocol, which comes really below this level. - if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) - resetTokenizer(); //VT100: CAN or SUB - if (cc != ESC) - { - processToken(TY_CTL(cc+'@' ),0,0); - return; - } - } - // advance the state - addToCurrentToken(cc); - - wchar_t* s = tokenBuffer; - int p = tokenBufferPos; - - if (getMode(MODE_Ansi)) - { - if (lec(1,0,ESC)) { return; } - if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } - if (les(2,1,GRP)) { return; } - if (Xte ) { processOSC(); resetTokenizer(); return; } - if (Xpe ) { prevCC = cc; return; } - if (lec(3,2,'?')) { return; } - if (lec(3,2,'>')) { return; } - if (lec(3,2,'!')) { return; } - if (lun( )) { processToken( TY_CHR(), applyCharset(cc), 0); resetTokenizer(); return; } - if (lec(2,0,ESC)) { processToken( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } - if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } - if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } - if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } - if (esp( )) { return; } - if (lec(5, 4, 'q') && s[3] == ' ') { - processToken( TY_CSI_PS_SP(cc, argv[0]), argv[0], 0); - resetTokenizer(); - return; + // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in + // VT100 This means, they do neither a resetTokenizer() nor a pushToToken(). + // Some of them, do of course. Guess this originates from a weakly layered + // handling of the X-on X-off protocol, which comes really below this level. + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) + resetTokenizer(); // VT100: CAN or SUB + if (cc != ESC) { + processToken(TY_CTL(cc + '@'), 0, 0); + return; + } } + // advance the state + addToCurrentToken(cc); - // resize = \e[8;;t - if (eps(CPS)) - { - processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); - resetTokenizer(); - return; - } + wchar_t *s = tokenBuffer; + int p = tokenBufferPos; + + if (getMode(MODE_Ansi)) { + if (lec(1, 0, ESC)) { + return; + } + if (lec(1, 0, ESC + 128)) { + s[0] = ESC; + receiveChar('['); + return; + } + if (les(2, 1, GRP)) { + return; + } + if (Xte) { + processOSC(); + resetTokenizer(); + return; + } + if (Xpe) { + prevCC = cc; + return; + } + if (lec(3, 2, '?')) { + return; + } + if (lec(3, 2, '>')) { + return; + } + if (lec(3, 2, '!')) { + return; + } + if (lun()) { + processToken(TY_CHR(), applyCharset(cc), 0); + resetTokenizer(); + return; + } + if (lec(2, 0, ESC)) { + processToken(TY_ESC(s[1]), 0, 0); + resetTokenizer(); + return; + } + if (les(3, 1, SCS)) { + processToken(TY_ESC_CS(s[1], s[2]), 0, 0); + resetTokenizer(); + return; + } + if (lec(3, 1, '#')) { + processToken(TY_ESC_DE(s[2]), 0, 0); + resetTokenizer(); + return; + } + if (eps(CPN)) { + processToken(TY_CSI_PN(cc), argv[0], argv[1]); + resetTokenizer(); + return; + } + if (esp()) { + return; + } + if (lec(5, 4, 'q') && s[3] == ' ') { + processToken(TY_CSI_PS_SP(cc, argv[0]), argv[0], 0); + resetTokenizer(); + return; + } + + // resize = \e[8;;t + if (eps(CPS)) { + processToken(TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); + resetTokenizer(); + return; + } - if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; } - if (ees(DIG)) { addDigit(cc-'0'); return; } - if (eec(';') || eec(':')) { addArgument(); return; } - for (int i=0;i<=argc;i++) - { - if (epp()) - processToken( TY_CSI_PR(cc,argv[i]), 0, 0); - else if (egt()) - processToken( TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c - else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) - { - // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m - i += 2; - processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); - i += 2; + if (epe()) { + processToken(TY_CSI_PE(cc), 0, 0); + resetTokenizer(); + return; } - else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) - { - // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m - i += 2; - processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); + if (ees(DIG)) { + addDigit(cc - '0'); + return; + } + if (eec(';') || eec(':')) { + addArgument(); + return; + } + for (int i = 0; i <= argc; i++) { + if (epp()) + processToken(TY_CSI_PR(cc, argv[i]), 0, 0); + else if (egt()) + processToken(TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c + else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && + argv[i + 1] == 2) { + // ESC[ ... 48;2;;; ... m -or- ESC[ ... + // 38;2;;; ... m + i += 2; + processToken(TY_CSI_PS(cc, argv[i - 2]), COLOR_SPACE_RGB, + (argv[i] << 16) | (argv[i + 1] << 8) | argv[i + 2]); + i += 2; + } else if (cc == 'm' && argc - i >= 2 && + (argv[i] == 38 || argv[i] == 48) && argv[i + 1] == 5) { + // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m + i += 2; + processToken(TY_CSI_PS(cc, argv[i - 2]), COLOR_SPACE_256, argv[i]); + } else + processToken(TY_CSI_PS(cc, argv[i]), 0, 0); } - else - processToken( TY_CSI_PS(cc,argv[i]), 0, 0); - } - resetTokenizer(); - } - else - { - // VT52 Mode - if (lec(1,0,ESC)) - return; - if (les(1,0,CHR)) - { - processToken( TY_CHR(), s[0], 0); resetTokenizer(); - return; - } - if (lec(2,1,'Y')) - return; - if (lec(3,1,'Y')) - return; - if (p < 4) - { - processToken( TY_VT52(s[1] ), 0, 0); + } else { + // VT52 Mode + if (lec(1, 0, ESC)) + return; + if (les(1, 0, CHR)) { + processToken(TY_CHR(), s[0], 0); + resetTokenizer(); + return; + } + if (lec(2, 1, 'Y')) + return; + if (lec(3, 1, 'Y')) + return; + if (p < 4) { + processToken(TY_VT52(s[1]), 0, 0); + resetTokenizer(); + return; + } + processToken(TY_VT52(s[1]), s[2], s[3]); resetTokenizer(); return; } - processToken( TY_VT52(s[1]), s[2], s[3]); - resetTokenizer(); - return; - } } -void Vt102Emulation::processOSC() -{ +void Vt102Emulation::processOSC() { QString token = QString::fromWCharArray(tokenBuffer, tokenBufferPos); int i = 2; while (i < tokenBufferPos && tokenBuffer[i] != ';') @@ -389,95 +421,104 @@ void Vt102Emulation::processOSC() } int command = -1; - switch (i-1) { - case 2: - command = tokenBuffer[2] - L'0'; - break; - case 3: - command = 10 * (tokenBuffer[2] - L'0') + (tokenBuffer[3] - L'0'); - break; - default: - reportDecodingError(); - return; + switch (i - 1) { + case 2: + command = tokenBuffer[2] - L'0'; + break; + case 3: + command = 10 * (tokenBuffer[2] - L'0') + (tokenBuffer[3] - L'0'); + break; + default: + reportDecodingError(); + return; } switch (command) { - /* - * Operating System Controls https://www.xfree86.org/current/ctlseqs.html - * - * Ps = 0 → Change Icon Name and Window Title to Pt - * Ps = 1 → Change Icon Name to Pt - * Ps = 2 → Change Window Title to Pt + /* + * Operating System Controls https://www.xfree86.org/current/ctlseqs.html + * + * Ps = 0 → Change Icon Name and Window Title to Pt + * Ps = 1 → Change Icon Name to Pt + * Ps = 2 → Change Window Title to Pt + */ + case 0: + case 1: + case 2: { + QString newValue = + QString::fromWCharArray(tokenBuffer + 3 + 1, tokenBufferPos - 3 - 2); + processWindowAttributeChange(command, newValue); + break; + } + // Ps = 52 → Manipulate Selection Data. These controls may be disabled using + // the allowWindowOps resource. + case 52: { + /* The first, Pc , may contain any character from the set c p s 0 1 2 3 4 5 + * 6 7 . It is used to construct a list of selection parameters for + * clipboard, primary, select, or cut buffers 0 through 8 respectively, in + * the order given. If the parameter is empty, xterm uses s 0 , to specify + * the configurable primary/clipboard selection and cut buffer 0. The second + * parameter, Pd , gives the selection data. Normally this is a string + * encoded in base64. The data becomes the new selection, which is then + * available for pasting by other applications. If the second parameter is a + * ? , xterm replies to the host with the selection data encoded using the + * same protocol. */ - case 0: - case 1: - case 2: { - QString newValue = QString::fromWCharArray(tokenBuffer + 3 + 1, tokenBufferPos-3-2); - processWindowAttributeChange(command,newValue); - break; - } - // Ps = 52 → Manipulate Selection Data. These controls may be disabled using the allowWindowOps resource. - case 52: { - /* The first, Pc , may contain any character from the set c p s 0 1 2 3 4 5 6 7 . It is used to construct a list of selection parameters for clipboard, primary, select, or cut buffers 0 through 8 respectively, in the order given. If the parameter is empty, xterm uses s 0 , to specify the configurable primary/clipboard selection and cut buffer 0. - * The second parameter, Pd , gives the selection data. Normally this is a string encoded in base64. The data becomes the new selection, which is then available for pasting by other applications. - * If the second parameter is a ? , xterm replies to the host with the selection data encoded using the same protocol. - */ - QString arg = QString::fromWCharArray(tokenBuffer + 4 + 1, tokenBufferPos-4-2); - QStringList args = arg.split(";", Qt::SkipEmptyParts); - auto processOSC52Text = [&](QString base64, QClipboard::Mode mode) { - QClipboard *clipboard = QApplication::clipboard(); - if(base64 == "!") { - clipboard->clear(mode); - } else { - QByteArray data = QByteArray::fromBase64(base64.toUtf8()); - clipboard->setText(QString::fromUtf8(data), mode); - } - }; - if(args.size() == 1 && args.at(0) != "?") { - processOSC52Text(args.at(0), QClipboard::Clipboard); - } else if(args.size() == 2) { - if(args.at(0) == "c" && args.at(1) != "?") { + QString arg = + QString::fromWCharArray(tokenBuffer + 4 + 1, tokenBufferPos - 4 - 2); + QStringList args = arg.split(";", Qt::SkipEmptyParts); + auto processOSC52Text = [&](QString base64, QClipboard::Mode mode) { + QClipboard *clipboard = QApplication::clipboard(); + if (base64 == "!") { + clipboard->clear(mode); + } else { + QByteArray data = QByteArray::fromBase64(base64.toUtf8()); + clipboard->setText(QString::fromUtf8(data), mode); + } + }; + if (args.size() == 1 && args.at(0) != "?") { + processOSC52Text(args.at(0), QClipboard::Clipboard); + } else if (args.size() == 2) { + if (args.at(0) == "c" && args.at(1) != "?") { processOSC52Text(args.at(1), QClipboard::Clipboard); - } - if(QApplication::clipboard()->supportsSelection()) { - if(args.at(0) == "p" && args.at(1) != "?") { - processOSC52Text(args.at(1), QClipboard::Selection); + } + if (QApplication::clipboard()->supportsSelection()) { + if (args.at(0) == "p" && args.at(1) != "?") { + processOSC52Text(args.at(1), QClipboard::Selection); } - } } - break; } - default: - reportDecodingError(); - break; + break; + } + default: + reportDecodingError(); + break; } } -void Vt102Emulation::processWindowAttributeChange(int attributeToChange, QString newValue) -{ - _pendingTitleUpdates[attributeToChange] = newValue; - _titleUpdateTimer->start(20); +void Vt102Emulation::processWindowAttributeChange(int attributeToChange, QString newValue) { + _pendingTitleUpdates[attributeToChange] = newValue; + _titleUpdateTimer->start(20); } -void Vt102Emulation::updateTitle() -{ - QListIterator iter( _pendingTitleUpdates.keys() ); +void Vt102Emulation::updateTitle() { + QListIterator iter(_pendingTitleUpdates.keys()); while (iter.hasNext()) { int arg = iter.next(); - doTitleChanged( arg , _pendingTitleUpdates[arg] ); + doTitleChanged(arg, _pendingTitleUpdates[arg]); } _pendingTitleUpdates.clear(); } -void Vt102Emulation::doTitleChanged( int what, const QString & caption ) -{ - //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) +void Vt102Emulation::doTitleChanged(int what, const QString &caption) { + // set to true if anything is actually changed (eg. old _nameTitle != new + // _nameTitle ) bool modified = false; - // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _nameTitle + // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only + // _nameTitle if ((what == 0) || (what == 2)) { _isTitleChanged = true; - if ( _userTitle != caption ) { + if (_userTitle != caption) { _userTitle = caption; modified = true; } @@ -485,14 +526,14 @@ void Vt102Emulation::doTitleChanged( int what, const QString & caption ) if ((what == 0) || (what == 1)) { _isTitleChanged = true; - if ( _iconText != caption ) { + if (_iconText != caption) { _iconText = caption; modified = true; } } if (what == 11) { - QString colorString = caption.section(QLatin1Char(';'),0,0); + QString colorString = caption.section(QLatin1Char(';'), 0, 0); QColor backColor = QColor(colorString); if (backColor.isValid()) { // change color via \033]11;Color\007 if (backColor != _modifiedBackground) { @@ -504,22 +545,23 @@ void Vt102Emulation::doTitleChanged( int what, const QString & caption ) if (what == 30) { _isTitleChanged = true; - if ( _nameTitle != caption ) { - _nameTitle=caption; + if (_nameTitle != caption) { + _nameTitle = caption; return; } } if (what == 31) { - QString cwd=caption; - cwd=cwd.replace( QRegularExpression(QLatin1String("^~")), QDir::homePath() ); + QString cwd = caption; + cwd = + cwd.replace(QRegularExpression(QLatin1String("^~")), QDir::homePath()); emit openUrlRequest(cwd); } // change icon via \033]32;Icon\007 if (what == 32) { _isTitleChanged = true; - if ( _iconName != caption ) { + if (_iconName != caption) { _iconName = caption; modified = true; @@ -531,539 +573,1052 @@ void Vt102Emulation::doTitleChanged( int what, const QString & caption ) return; } - if ( modified ) { - emit titleChanged(what,caption); + if (modified) { + emit titleChanged(what, caption); } } // Interpreting Codes --------------------------------------------------------- /* - Now that the incoming character stream is properly tokenized, - meaning is assigned to them. These are either operations of - the current _screen, or of the emulation class itself. + Now that the incoming character stream is properly tokenized, + meaning is assigned to them. These are either operations of + the current _screen, or of the emulation class itself. - The token to be interpreteted comes in as a machine word - possibly accompanied by two parameters. + The token to be interpreteted comes in as a machine word + possibly accompanied by two parameters. - Likewise, the operations assigned to, come with up to two - arguments. One could consider to make up a proper table - from the function below. + Likewise, the operations assigned to, come with up to two + arguments. One could consider to make up a proper table + from the function below. - The technical reference manual provides more information - about this mapping. + The technical reference manual provides more information + about this mapping. */ -void Vt102Emulation::processToken(int token, wchar_t p, int q) -{ - switch (token) - { - case TY_CHR( ) : _currentScreen->displayCharacter (p );dupDisplayCharacter(p); break; //UTF16 - - // 127 DEL : ignored on input - - case TY_CTL('@' ) : /* NUL: ignored */ break; - case TY_CTL('A' ) : /* SOH: ignored */ break; - case TY_CTL('B' ) : /* STX: ignored */ break; - case TY_CTL('C' ) : /* ETX: ignored */ break; - case TY_CTL('D' ) : /* EOT: ignored */ break; - case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 - case TY_CTL('F' ) : /* ACK: ignored */ break; - case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); - break; //VT100 - case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 - case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 - case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 - case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 - case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 - case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 - - case TY_CTL('N' ) : useCharset ( 1); break; //VT100 - case TY_CTL('O' ) : useCharset ( 0); break; //VT100 - - case TY_CTL('P' ) : /* DLE: ignored */ break; - case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 - case TY_CTL('R' ) : /* DC2: ignored */ break; - case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 - case TY_CTL('T' ) : /* DC4: ignored */ break; - case TY_CTL('U' ) : /* NAK: ignored */ break; - case TY_CTL('V' ) : /* SYN: ignored */ break; - case TY_CTL('W' ) : /* ETB: ignored */ break; - case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592);dupDisplayCharacter(0x2592); break; //VT100 - case TY_CTL('Y' ) : /* EM : ignored */ break; - case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592);dupDisplayCharacter(0x2592); break; //VT100 - case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; - case TY_CTL('\\' ) : /* FS : ignored */ break; - case TY_CTL(']' ) : /* GS : ignored */ break; - case TY_CTL('^' ) : /* RS : ignored */ break; - case TY_CTL('_' ) : /* US : ignored */ break; - - case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 - case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 - case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 - case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 - case TY_ESC('Z' ) : reportTerminalType ( ); break; - case TY_ESC('c' ) : reset ( ); break; - - case TY_ESC('n' ) : useCharset ( 2); break; - case TY_ESC('o' ) : useCharset ( 3); break; - case TY_ESC('7' ) : saveCursor ( ); break; - case TY_ESC('8' ) : restoreCursor ( ); break; - - case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; - case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; - case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 - - case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 - case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 - case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 - - case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 - case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 - case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 - - case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 - case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 - case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 - - case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 - case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 - case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 - - case TY_ESC_CS('%', 'G') : /*No longer updating codec*/ break; //LINUX - case TY_ESC_CS('%', '@') : /*No longer updating codec*/ break; //LINUX - - case TY_ESC_DE('3' ) : /* Double height line, top half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; - case TY_ESC_DE('4' ) : /* Double height line, bottom half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; - case TY_ESC_DE('5' ) : /* Single width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; - case TY_ESC_DE('6' ) : /* Double width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; - case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; - -// resize = \e[8;;t - case TY_CSI_PS('t', 8) : setImageSize( p /*lines */, q /* columns */ ); - emit imageResizeRequest(QSize(q, p)); - break; - -// change tab text color : \e[28;t color: 0-16,777,215 - case TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; - - case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; - case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; - case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; - case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; - case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; - case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; - case TY_CSI_PS('J', 3) : clearHistory(); break; - case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 - case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 - case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; - case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; - case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 - case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; - case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; - case TY_CSI_PS('s', 0) : saveCursor ( ); break; - case TY_CSI_PS('u', 0) : restoreCursor ( ); break; - - case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; - case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 - case TY_CSI_PS('m', 2) : _currentScreen-> setRendition (RE_FAINT ); break; - case TY_CSI_PS('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); break; //VT100 - case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 - case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 - case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; - case TY_CSI_PS('m', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; - case TY_CSI_PS('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; - case TY_CSI_PS('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); break; - case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX - case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX - case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX - case TY_CSI_PS('m', 21) : _currentScreen->resetRendition (RE_BOLD ); break; - case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); - _currentScreen->resetRendition (RE_FAINT ); break; - case TY_CSI_PS('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 - case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; - case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; - case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; - case TY_CSI_PS('m', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; - case TY_CSI_PS('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; - case TY_CSI_PS('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); break; - - case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; - case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; - case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; - case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; - case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; - case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; - case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; - case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; - - case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; - - case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; - - case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; - case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; - case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; - case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; - case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; - case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; - case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; - case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; - - case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; - - case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; - - case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; - case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; - case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; - case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; - case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; - case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; - case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; - case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; - - case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; - case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; - case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; - case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; - case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; - case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; - case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; - case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; - - case TY_CSI_PS('n', 5) : reportStatus ( ); break; - case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; - case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 - case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 - case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 - case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 - case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 - case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 - case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 - - case TY_CSI_PS_SP('q', 0) : /* fall through */ - case TY_CSI_PS_SP('q', 1) : emit cursorChanged(KeyboardCursorShape::BlockCursor, true ); break; - case TY_CSI_PS_SP('q', 2) : emit cursorChanged(KeyboardCursorShape::BlockCursor, false); break; - case TY_CSI_PS_SP('q', 3) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, true ); break; - case TY_CSI_PS_SP('q', 4) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, false); break; - case TY_CSI_PS_SP('q', 5) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, true ); break; - case TY_CSI_PS_SP('q', 6) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, false); break; - - case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; - case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 - case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 - case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 - case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 - case TY_CSI_PN('E' ) : _currentScreen->cursorNextLine (p ); break; //VT100 - case TY_CSI_PN('F' ) : _currentScreen->cursorPreviousLine (p ); break; //VT100 - case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX - case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 - case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; - case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; - case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; - case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; - case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; - case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; - case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; - case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; - case TY_CSI_PN('b' ) : _currentScreen->repeatChars (p ); break; - case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 - case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX - case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 - case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 - case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 - - case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 - case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 - case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME - case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME - - case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 - - case TY_CSI_PR('h', 3) : setMode (MODE_132Columns);break; //VT100 - case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns);break; //VT100 - - case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 - case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 - - case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 - case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 - - case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 - case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 - case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME - case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME - - case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 - case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 - case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME - case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME - - case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 - case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 - case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 - case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 - - case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 - case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 - case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 - case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 - - case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 - case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 - case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 - case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 - - case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 - case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 - case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 - case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 - - case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM - case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM - - case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - - case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 - case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 - case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM - case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM - - case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM - case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM - case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM - case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ break; //XTERM - - // XTerm defines the following modes: - // SET_VT200_MOUSE 1000 - // SET_VT200_HIGHLIGHT_MOUSE 1001 - // SET_BTN_EVENT_MOUSE 1002 - // SET_ANY_EVENT_MOUSE 1003 - // - - //Note about mouse modes: - //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 - //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). - //TODO: Implementation of mouse modes 1001 (something called highlight tracking) and - //1003 (a slight variation on dragging the mouse) - // - - case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM - case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM - case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM - case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM - - case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM - case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM - case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM - case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM - - case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM - case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM - case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM - case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM - - case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM - case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM - case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM - case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM - - case TY_CSI_PR('h', 1004) : _reportFocusEvents = true; break; - case TY_CSI_PR('l', 1004) : _reportFocusEvents = false; break; - - case TY_CSI_PR('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM - case TY_CSI_PR('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM - case TY_CSI_PR('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM - case TY_CSI_PR('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM - - case TY_CSI_PR('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM - case TY_CSI_PR('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM - case TY_CSI_PR('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM - case TY_CSI_PR('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM - - case TY_CSI_PR('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT - case TY_CSI_PR('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT - case TY_CSI_PR('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT - case TY_CSI_PR('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT - - case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM - - case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM - case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM - case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM - case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM - - //FIXME: Unitoken: save translations - case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM - case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM - case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM - case TY_CSI_PR('r', 1048) : restoreCursor ( ); break; //XTERM - - //FIXME: every once new sequences like this pop up in xterm. - // Here's a guess of what they could mean. - case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM - case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM - - case TY_CSI_PR('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM - case TY_CSI_PR('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM - case TY_CSI_PR('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM - case TY_CSI_PR('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM - - //FIXME: weird DEC reset sequence - case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; - - //FIXME: when changing between vt52 and ansi mode evtl do some resetting. - case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 - case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 - case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 - case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 - - case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 - case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 - - case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 - case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 - case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 - case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 - case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 - case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 - case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 - case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 - case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 - - case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 +void Vt102Emulation::processToken(int token, wchar_t p, int q) { + switch (token) { + case TY_CHR(): + _currentScreen->displayCharacter(p); + dupDisplayCharacter(p); + break; // UTF16 + + // 127 DEL : ignored on input + + case TY_CTL('@'): /* NUL: ignored */ + break; + case TY_CTL('A'): /* SOH: ignored */ + break; + case TY_CTL('B'): /* STX: ignored */ + break; + case TY_CTL('C'): /* ETX: ignored */ + break; + case TY_CTL('D'): /* EOT: ignored */ + break; + case TY_CTL('E'): + reportAnswerBack(); + break; // VT100 + case TY_CTL('F'): /* ACK: ignored */ + break; + case TY_CTL('G'): + emit stateSet(NOTIFYBELL); + break; // VT100 + case TY_CTL('H'): + _currentScreen->backspace(); + break; // VT100 + case TY_CTL('I'): + _currentScreen->tab(); + break; // VT100 + case TY_CTL('J'): + _currentScreen->newLine(); + break; // VT100 + case TY_CTL('K'): + _currentScreen->newLine(); + break; // VT100 + case TY_CTL('L'): + _currentScreen->newLine(); + break; // VT100 + case TY_CTL('M'): + _currentScreen->toStartOfLine(); + break; // VT100 + + case TY_CTL('N'): + useCharset(1); + break; // VT100 + case TY_CTL('O'): + useCharset(0); + break; // VT100 + + case TY_CTL('P'): /* DLE: ignored */ + break; + case TY_CTL('Q'): /* DC1: XON continue */ + break; // VT100 + case TY_CTL('R'): /* DC2: ignored */ + break; + case TY_CTL('S'): /* DC3: XOFF halt */ + break; // VT100 + case TY_CTL('T'): /* DC4: ignored */ + break; + case TY_CTL('U'): /* NAK: ignored */ + break; + case TY_CTL('V'): /* SYN: ignored */ + break; + case TY_CTL('W'): /* ETB: ignored */ + break; + case TY_CTL('X'): + _currentScreen->displayCharacter(0x2592); + dupDisplayCharacter(0x2592); + break; // VT100 + case TY_CTL('Y'): /* EM : ignored */ + break; + case TY_CTL('Z'): + _currentScreen->displayCharacter(0x2592); + dupDisplayCharacter(0x2592); + break; // VT100 + case TY_CTL('['): /* ESC: cannot be seen here. */ + break; + case TY_CTL('\\'): /* FS : ignored */ + break; + case TY_CTL(']'): /* GS : ignored */ + break; + case TY_CTL('^'): /* RS : ignored */ + break; + case TY_CTL('_'): /* US : ignored */ + break; + + case TY_ESC('D'): + _currentScreen->index(); + break; // VT100 + case TY_ESC('E'): + _currentScreen->nextLine(); + break; // VT100 + case TY_ESC('H'): + _currentScreen->changeTabStop(true); + break; // VT100 + case TY_ESC('M'): + _currentScreen->reverseIndex(); + break; // VT100 + case TY_ESC('Z'): + reportTerminalType(); + break; + case TY_ESC('c'): + reset(); + break; + + case TY_ESC('n'): + useCharset(2); + break; + case TY_ESC('o'): + useCharset(3); + break; + case TY_ESC('7'): + saveCursor(); + break; + case TY_ESC('8'): + restoreCursor(); + break; + + case TY_ESC('='): + setMode(MODE_AppKeyPad); + break; + case TY_ESC('>'): + resetMode(MODE_AppKeyPad); + break; + case TY_ESC('<'): + setMode(MODE_Ansi); + break; // VT100 + + case TY_ESC_CS('(', '0'): + setCharset(0, '0'); + break; // VT100 + case TY_ESC_CS('(', 'A'): + setCharset(0, 'A'); + break; // VT100 + case TY_ESC_CS('(', 'B'): + setCharset(0, 'B'); + break; // VT100 + + case TY_ESC_CS(')', '0'): + setCharset(1, '0'); + break; // VT100 + case TY_ESC_CS(')', 'A'): + setCharset(1, 'A'); + break; // VT100 + case TY_ESC_CS(')', 'B'): + setCharset(1, 'B'); + break; // VT100 + + case TY_ESC_CS('*', '0'): + setCharset(2, '0'); + break; // VT100 + case TY_ESC_CS('*', 'A'): + setCharset(2, 'A'); + break; // VT100 + case TY_ESC_CS('*', 'B'): + setCharset(2, 'B'); + break; // VT100 + + case TY_ESC_CS('+', '0'): + setCharset(3, '0'); + break; // VT100 + case TY_ESC_CS('+', 'A'): + setCharset(3, 'A'); + break; // VT100 + case TY_ESC_CS('+', 'B'): + setCharset(3, 'B'); + break; // VT100 + + case TY_ESC_CS('%', 'G'): /*No longer updating codec*/ + break; // LINUX + case TY_ESC_CS('%', '@'): /*No longer updating codec*/ + break; // LINUX + + case TY_ESC_DE('3'): /* Double height line, top half */ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT, true); + break; + case TY_ESC_DE('4'): /* Double height line, bottom half */ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT, true); + break; + case TY_ESC_DE('5'): /* Single width, single height line*/ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, false); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT, false); + break; + case TY_ESC_DE('6'): /* Double width, single height line*/ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT, false); + break; + case TY_ESC_DE('8'): + _currentScreen->helpAlign(); + break; + + // resize = \e[8;;t + case TY_CSI_PS('t', 8): + setImageSize(p /*lines */, q /* columns */); + emit imageResizeRequest(QSize(q, p)); + break; + + // change tab text color : \e[28;t color: 0-16,777,215 + case TY_CSI_PS('t', 28): + emit changeTabTextColorRequest(p); + break; + + case TY_CSI_PS('K', 0): + _currentScreen->clearToEndOfLine(); + break; + case TY_CSI_PS('K', 1): + _currentScreen->clearToBeginOfLine(); + break; + case TY_CSI_PS('K', 2): + _currentScreen->clearEntireLine(); + break; + case TY_CSI_PS('J', 0): + _currentScreen->clearToEndOfScreen(); + break; + case TY_CSI_PS('J', 1): + _currentScreen->clearToBeginOfScreen(); + break; + case TY_CSI_PS('J', 2): + _currentScreen->clearEntireScreen(); + break; + case TY_CSI_PS('J', 3): + clearHistory(); + break; + case TY_CSI_PS('g', 0): + _currentScreen->changeTabStop(false); + break; // VT100 + case TY_CSI_PS('g', 3): + _currentScreen->clearTabStops(); + break; // VT100 + case TY_CSI_PS('h', 4): + _currentScreen->setMode(MODE_Insert); + break; + case TY_CSI_PS('h', 20): + setMode(MODE_NewLine); + break; + case TY_CSI_PS('i', 0): /* IGNORE: attached printer */ + break; // VT100 + case TY_CSI_PS('l', 4): + _currentScreen->resetMode(MODE_Insert); + break; + case TY_CSI_PS('l', 20): + resetMode(MODE_NewLine); + break; + case TY_CSI_PS('s', 0): + saveCursor(); + break; + case TY_CSI_PS('u', 0): + restoreCursor(); + break; + + case TY_CSI_PS('m', 0): + _currentScreen->setDefaultRendition(); + break; + case TY_CSI_PS('m', 1): + _currentScreen->setRendition(RE_BOLD); + break; // VT100 + case TY_CSI_PS('m', 2): + _currentScreen->setRendition(RE_FAINT); + break; + case TY_CSI_PS('m', 3): + _currentScreen->setRendition(RE_ITALIC); + break; // VT100 + case TY_CSI_PS('m', 4): + _currentScreen->setRendition(RE_UNDERLINE); + break; // VT100 + case TY_CSI_PS('m', 5): + _currentScreen->setRendition(RE_BLINK); + break; // VT100 + case TY_CSI_PS('m', 7): + _currentScreen->setRendition(RE_REVERSE); + break; + case TY_CSI_PS('m', 8): + _currentScreen->setRendition(RE_CONCEAL); + break; + case TY_CSI_PS('m', 9): + _currentScreen->setRendition(RE_STRIKEOUT); + break; + case TY_CSI_PS('m', 53): + _currentScreen->setRendition(RE_OVERLINE); + break; + case TY_CSI_PS('m', 10): /* IGNORED: mapping related */ + break; // LINUX + case TY_CSI_PS('m', 11): /* IGNORED: mapping related */ + break; // LINUX + case TY_CSI_PS('m', 12): /* IGNORED: mapping related */ + break; // LINUX + case TY_CSI_PS('m', 21): + _currentScreen->resetRendition(RE_BOLD); + break; + case TY_CSI_PS('m', 22): + _currentScreen->resetRendition(RE_BOLD); + _currentScreen->resetRendition(RE_FAINT); + break; + case TY_CSI_PS('m', 23): + _currentScreen->resetRendition(RE_ITALIC); + break; // VT100 + case TY_CSI_PS('m', 24): + _currentScreen->resetRendition(RE_UNDERLINE); + break; + case TY_CSI_PS('m', 25): + _currentScreen->resetRendition(RE_BLINK); + break; + case TY_CSI_PS('m', 27): + _currentScreen->resetRendition(RE_REVERSE); + break; + case TY_CSI_PS('m', 28): + _currentScreen->resetRendition(RE_CONCEAL); + break; + case TY_CSI_PS('m', 29): + _currentScreen->resetRendition(RE_STRIKEOUT); + break; + case TY_CSI_PS('m', 55): + _currentScreen->resetRendition(RE_OVERLINE); + break; + + case TY_CSI_PS('m', 30): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 0); + break; + case TY_CSI_PS('m', 31): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 1); + break; + case TY_CSI_PS('m', 32): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 2); + break; + case TY_CSI_PS('m', 33): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 3); + break; + case TY_CSI_PS('m', 34): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 4); + break; + case TY_CSI_PS('m', 35): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 5); + break; + case TY_CSI_PS('m', 36): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 6); + break; + case TY_CSI_PS('m', 37): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 7); + break; + + case TY_CSI_PS('m', 38): + _currentScreen->setForeColor(p, q); + break; + + case TY_CSI_PS('m', 39): + _currentScreen->setForeColor(COLOR_SPACE_DEFAULT, 0); + break; + + case TY_CSI_PS('m', 40): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 0); + break; + case TY_CSI_PS('m', 41): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 1); + break; + case TY_CSI_PS('m', 42): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 2); + break; + case TY_CSI_PS('m', 43): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 3); + break; + case TY_CSI_PS('m', 44): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 4); + break; + case TY_CSI_PS('m', 45): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 5); + break; + case TY_CSI_PS('m', 46): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 6); + break; + case TY_CSI_PS('m', 47): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 7); + break; + + case TY_CSI_PS('m', 48): + _currentScreen->setBackColor(p, q); + break; + + case TY_CSI_PS('m', 49): + _currentScreen->setBackColor(COLOR_SPACE_DEFAULT, 1); + break; + + case TY_CSI_PS('m', 90): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 8); + break; + case TY_CSI_PS('m', 91): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 9); + break; + case TY_CSI_PS('m', 92): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 10); + break; + case TY_CSI_PS('m', 93): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 11); + break; + case TY_CSI_PS('m', 94): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 12); + break; + case TY_CSI_PS('m', 95): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 13); + break; + case TY_CSI_PS('m', 96): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 14); + break; + case TY_CSI_PS('m', 97): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 15); + break; + + case TY_CSI_PS('m', 100): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 8); + break; + case TY_CSI_PS('m', 101): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 9); + break; + case TY_CSI_PS('m', 102): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 10); + break; + case TY_CSI_PS('m', 103): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 11); + break; + case TY_CSI_PS('m', 104): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 12); + break; + case TY_CSI_PS('m', 105): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 13); + break; + case TY_CSI_PS('m', 106): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 14); + break; + case TY_CSI_PS('m', 107): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 15); + break; + + case TY_CSI_PS('n', 5): + reportStatus(); + break; + case TY_CSI_PS('n', 6): + reportCursorPosition(); + break; + case TY_CSI_PS('q', 0): /* IGNORED: LEDs off */ + break; // VT100 + case TY_CSI_PS('q', 1): /* IGNORED: LED1 on */ + break; // VT100 + case TY_CSI_PS('q', 2): /* IGNORED: LED2 on */ + break; // VT100 + case TY_CSI_PS('q', 3): /* IGNORED: LED3 on */ + break; // VT100 + case TY_CSI_PS('q', 4): /* IGNORED: LED4 on */ + break; // VT100 + case TY_CSI_PS('x', 0): + reportTerminalParms(2); + break; // VT100 + case TY_CSI_PS('x', 1): + reportTerminalParms(3); + break; // VT100 + + case TY_CSI_PS_SP('q', 0): /* fall through */ + case TY_CSI_PS_SP('q', 1): + emit cursorChanged(KeyboardCursorShape::BlockCursor, true); + break; + case TY_CSI_PS_SP('q', 2): + emit cursorChanged(KeyboardCursorShape::BlockCursor, false); + break; + case TY_CSI_PS_SP('q', 3): + emit cursorChanged(KeyboardCursorShape::UnderlineCursor, true); + break; + case TY_CSI_PS_SP('q', 4): + emit cursorChanged(KeyboardCursorShape::UnderlineCursor, false); + break; + case TY_CSI_PS_SP('q', 5): + emit cursorChanged(KeyboardCursorShape::IBeamCursor, true); + break; + case TY_CSI_PS_SP('q', 6): + emit cursorChanged(KeyboardCursorShape::IBeamCursor, false); + break; + + case TY_CSI_PN('@'): + _currentScreen->insertChars(p); + break; + case TY_CSI_PN('A'): + _currentScreen->cursorUp(p); + break; // VT100 + case TY_CSI_PN('B'): + _currentScreen->cursorDown(p); + break; // VT100 + case TY_CSI_PN('C'): + _currentScreen->cursorRight(p); + break; // VT100 + case TY_CSI_PN('D'): + _currentScreen->cursorLeft(p); + break; // VT100 + case TY_CSI_PN('E'): + _currentScreen->cursorNextLine(p); + break; // VT100 + case TY_CSI_PN('F'): + _currentScreen->cursorPreviousLine(p); + break; // VT100 + case TY_CSI_PN('G'): + _currentScreen->setCursorX(p); + break; // LINUX + case TY_CSI_PN('H'): + _currentScreen->setCursorYX(p, q); + break; // VT100 + case TY_CSI_PN('I'): + _currentScreen->tab(p); + break; + case TY_CSI_PN('L'): + _currentScreen->insertLines(p); + break; + case TY_CSI_PN('M'): + _currentScreen->deleteLines(p); + break; + case TY_CSI_PN('P'): + _currentScreen->deleteChars(p); + break; + case TY_CSI_PN('S'): + _currentScreen->scrollUp(p); + break; + case TY_CSI_PN('T'): + _currentScreen->scrollDown(p); + break; + case TY_CSI_PN('X'): + _currentScreen->eraseChars(p); + break; + case TY_CSI_PN('Z'): + _currentScreen->backtab(p); + break; + case TY_CSI_PN('b'): + _currentScreen->repeatChars(p); + break; + case TY_CSI_PN('c'): + reportTerminalType(); + break; // VT100 + case TY_CSI_PN('d'): + _currentScreen->setCursorY(p); + break; // LINUX + case TY_CSI_PN('f'): + _currentScreen->setCursorYX(p, q); + break; // VT100 + case TY_CSI_PN('r'): + setMargins(p, q); + break; // VT100 + case TY_CSI_PN('y'): /* IGNORED: Confidence test */ + break; // VT100 + + case TY_CSI_PR('h', 1): + setMode(MODE_AppCuKeys); + break; // VT100 + case TY_CSI_PR('l', 1): + resetMode(MODE_AppCuKeys); + break; // VT100 + case TY_CSI_PR('s', 1): + saveMode(MODE_AppCuKeys); + break; // FIXME + case TY_CSI_PR('r', 1): + restoreMode(MODE_AppCuKeys); + break; // FIXME + + case TY_CSI_PR('l', 2): + resetMode(MODE_Ansi); + break; // VT100 + + case TY_CSI_PR('h', 3): + setMode(MODE_132Columns); + break; // VT100 + case TY_CSI_PR('l', 3): + resetMode(MODE_132Columns); + break; // VT100 + + case TY_CSI_PR('h', 4): /* IGNORED: soft scrolling */ + break; // VT100 + case TY_CSI_PR('l', 4): /* IGNORED: soft scrolling */ + break; // VT100 + + case TY_CSI_PR('h', 5): + _currentScreen->setMode(MODE_Screen); + break; // VT100 + case TY_CSI_PR('l', 5): + _currentScreen->resetMode(MODE_Screen); + break; // VT100 + + case TY_CSI_PR('h', 6): + _currentScreen->setMode(MODE_Origin); + break; // VT100 + case TY_CSI_PR('l', 6): + _currentScreen->resetMode(MODE_Origin); + break; // VT100 + case TY_CSI_PR('s', 6): + _currentScreen->saveMode(MODE_Origin); + break; // FIXME + case TY_CSI_PR('r', 6): + _currentScreen->restoreMode(MODE_Origin); + break; // FIXME + + case TY_CSI_PR('h', 7): + _currentScreen->setMode(MODE_Wrap); + break; // VT100 + case TY_CSI_PR('l', 7): + _currentScreen->resetMode(MODE_Wrap); + break; // VT100 + case TY_CSI_PR('s', 7): + _currentScreen->saveMode(MODE_Wrap); + break; // FIXME + case TY_CSI_PR('r', 7): + _currentScreen->restoreMode(MODE_Wrap); + break; // FIXME + + case TY_CSI_PR('h', 8): /* IGNORED: autorepeat on */ + break; // VT100 + case TY_CSI_PR('l', 8): /* IGNORED: autorepeat off */ + break; // VT100 + case TY_CSI_PR('s', 8): /* IGNORED: autorepeat on */ + break; // VT100 + case TY_CSI_PR('r', 8): /* IGNORED: autorepeat off */ + break; // VT100 + + case TY_CSI_PR('h', 9): /* IGNORED: interlace */ + break; // VT100 + case TY_CSI_PR('l', 9): /* IGNORED: interlace */ + break; // VT100 + case TY_CSI_PR('s', 9): /* IGNORED: interlace */ + break; // VT100 + case TY_CSI_PR('r', 9): /* IGNORED: interlace */ + break; // VT100 + + case TY_CSI_PR('h', 12): /* IGNORED: Cursor blink */ + break; // att610 + case TY_CSI_PR('l', 12): /* IGNORED: Cursor blink */ + break; // att610 + case TY_CSI_PR('s', 12): /* IGNORED: Cursor blink */ + break; // att610 + case TY_CSI_PR('r', 12): /* IGNORED: Cursor blink */ + break; // att610 + + case TY_CSI_PR('h', 25): + setMode(MODE_Cursor); + break; // VT100 + case TY_CSI_PR('l', 25): + resetMode(MODE_Cursor); + break; // VT100 + case TY_CSI_PR('s', 25): + saveMode(MODE_Cursor); + break; // VT100 + case TY_CSI_PR('r', 25): + restoreMode(MODE_Cursor); + break; // VT100 + + case TY_CSI_PR('h', 40): + setMode(MODE_Allow132Columns); + break; // XTERM + case TY_CSI_PR('l', 40): + resetMode(MODE_Allow132Columns); + break; // XTERM + + case TY_CSI_PR('h', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case TY_CSI_PR('l', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case TY_CSI_PR('s', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case TY_CSI_PR('r', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + + case TY_CSI_PR('h', 47): + setMode(MODE_AppScreen); + break; // VT100 + case TY_CSI_PR('l', 47): + resetMode(MODE_AppScreen); + break; // VT100 + case TY_CSI_PR('s', 47): + saveMode(MODE_AppScreen); + break; // XTERM + case TY_CSI_PR('r', 47): + restoreMode(MODE_AppScreen); + break; // XTERM + + case TY_CSI_PR('h', 67): /* IGNORED: DECBKM */ + break; // XTERM + case TY_CSI_PR('l', 67): /* IGNORED: DECBKM */ + break; // XTERM + case TY_CSI_PR('s', 67): /* IGNORED: DECBKM */ + break; // XTERM + case TY_CSI_PR('r', 67): /* IGNORED: DECBKM */ + break; // XTERM + + // XTerm defines the following modes: + // SET_VT200_MOUSE 1000 + // SET_VT200_HIGHLIGHT_MOUSE 1001 + // SET_BTN_EVENT_MOUSE 1002 + // SET_ANY_EVENT_MOUSE 1003 + // + + // Note about mouse modes: + // There are four mouse modes which xterm-compatible terminals can support - + // 1000,1001,1002,1003 Konsole currently supports mode 1000 (basic mouse + // press and release) and mode 1002 (dragging the mouse). + // TODO: Implementation of mouse modes 1001 (something called highlight + // tracking) and 1003 (a slight variation on dragging the mouse) + // + + case TY_CSI_PR('h', 1000): + setMode(MODE_Mouse1000); + break; // XTERM + case TY_CSI_PR('l', 1000): + resetMode(MODE_Mouse1000); + break; // XTERM + case TY_CSI_PR('s', 1000): + saveMode(MODE_Mouse1000); + break; // XTERM + case TY_CSI_PR('r', 1000): + restoreMode(MODE_Mouse1000); + break; // XTERM + + case TY_CSI_PR('h', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM + case TY_CSI_PR('l', 1001): + resetMode(MODE_Mouse1001); + break; // XTERM + case TY_CSI_PR('s', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM + case TY_CSI_PR('r', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM + + case TY_CSI_PR('h', 1002): + setMode(MODE_Mouse1002); + break; // XTERM + case TY_CSI_PR('l', 1002): + resetMode(MODE_Mouse1002); + break; // XTERM + case TY_CSI_PR('s', 1002): + saveMode(MODE_Mouse1002); + break; // XTERM + case TY_CSI_PR('r', 1002): + restoreMode(MODE_Mouse1002); + break; // XTERM + + case TY_CSI_PR('h', 1003): + setMode(MODE_Mouse1003); + break; // XTERM + case TY_CSI_PR('l', 1003): + resetMode(MODE_Mouse1003); + break; // XTERM + case TY_CSI_PR('s', 1003): + saveMode(MODE_Mouse1003); + break; // XTERM + case TY_CSI_PR('r', 1003): + restoreMode(MODE_Mouse1003); + break; // XTERM + + case TY_CSI_PR('h', 1004): + _reportFocusEvents = true; + break; + case TY_CSI_PR('l', 1004): + _reportFocusEvents = false; + break; + + case TY_CSI_PR('h', 1005): + setMode(MODE_Mouse1005); + break; // XTERM + case TY_CSI_PR('l', 1005): + resetMode(MODE_Mouse1005); + break; // XTERM + case TY_CSI_PR('s', 1005): + saveMode(MODE_Mouse1005); + break; // XTERM + case TY_CSI_PR('r', 1005): + restoreMode(MODE_Mouse1005); + break; // XTERM + + case TY_CSI_PR('h', 1006): + setMode(MODE_Mouse1006); + break; // XTERM + case TY_CSI_PR('l', 1006): + resetMode(MODE_Mouse1006); + break; // XTERM + case TY_CSI_PR('s', 1006): + saveMode(MODE_Mouse1006); + break; // XTERM + case TY_CSI_PR('r', 1006): + restoreMode(MODE_Mouse1006); + break; // XTERM + + case TY_CSI_PR('h', 1015): + setMode(MODE_Mouse1015); + break; // URXVT + case TY_CSI_PR('l', 1015): + resetMode(MODE_Mouse1015); + break; // URXVT + case TY_CSI_PR('s', 1015): + saveMode(MODE_Mouse1015); + break; // URXVT + case TY_CSI_PR('r', 1015): + restoreMode(MODE_Mouse1015); + break; // URXVT + + case TY_CSI_PR('h', 1034): /* IGNORED: 8bitinput activation */ + break; // XTERM + + case TY_CSI_PR('h', 1047): + setMode(MODE_AppScreen); + break; // XTERM + case TY_CSI_PR('l', 1047): + _screen[1]->clearEntireScreen(); + resetMode(MODE_AppScreen); + break; // XTERM + case TY_CSI_PR('s', 1047): + saveMode(MODE_AppScreen); + break; // XTERM + case TY_CSI_PR('r', 1047): + restoreMode(MODE_AppScreen); + break; // XTERM + + // FIXME: Unitoken: save translations + case TY_CSI_PR('h', 1048): + saveCursor(); + break; // XTERM + case TY_CSI_PR('l', 1048): + restoreCursor(); + break; // XTERM + case TY_CSI_PR('s', 1048): + saveCursor(); + break; // XTERM + case TY_CSI_PR('r', 1048): + restoreCursor(); + break; // XTERM + + // FIXME: every once new sequences like this pop up in xterm. + // Here's a guess of what they could mean. + case TY_CSI_PR('h', 1049): + saveCursor(); + _screen[1]->clearEntireScreen(); + setMode(MODE_AppScreen); + break; // XTERM + case TY_CSI_PR('l', 1049): + resetMode(MODE_AppScreen); + restoreCursor(); + break; // XTERM + + case TY_CSI_PR('h', 2004): + setMode(MODE_BracketedPaste); + break; // XTERM + case TY_CSI_PR('l', 2004): + resetMode(MODE_BracketedPaste); + break; // XTERM + case TY_CSI_PR('s', 2004): + saveMode(MODE_BracketedPaste); + break; // XTERM + case TY_CSI_PR('r', 2004): + restoreMode(MODE_BracketedPaste); + break; // XTERM + + // FIXME: weird DEC reset sequence + case TY_CSI_PE('p'): /* IGNORED: reset ( ) */ + break; + + // FIXME: when changing between vt52 and ansi mode evtl do some resetting. + case TY_VT52('A'): + _currentScreen->cursorUp(1); + break; // VT52 + case TY_VT52('B'): + _currentScreen->cursorDown(1); + break; // VT52 + case TY_VT52('C'): + _currentScreen->cursorRight(1); + break; // VT52 + case TY_VT52('D'): + _currentScreen->cursorLeft(1); + break; // VT52 + + case TY_VT52('F'): + setAndUseCharset(0, '0'); + break; // VT52 + case TY_VT52('G'): + setAndUseCharset(0, 'B'); + break; // VT52 + + case TY_VT52('H'): + _currentScreen->setCursorYX(1, 1); + break; // VT52 + case TY_VT52('I'): + _currentScreen->reverseIndex(); + break; // VT52 + case TY_VT52('J'): + _currentScreen->clearToEndOfScreen(); + break; // VT52 + case TY_VT52('K'): + _currentScreen->clearToEndOfLine(); + break; // VT52 + case TY_VT52('Y'): + _currentScreen->setCursorYX(p - 31, q - 31); + break; // VT52 + case TY_VT52('Z'): + reportTerminalType(); + break; // VT52 + case TY_VT52('<'): + setMode(MODE_Ansi); + break; // VT52 + case TY_VT52('='): + setMode(MODE_AppKeyPad); + break; // VT52 + case TY_VT52('>'): + resetMode(MODE_AppKeyPad); + break; // VT52 + + case TY_CSI_PG('c'): + reportSecondaryAttributes(); + break; // VT100 default: reportDecodingError(); break; - }; + }; } -void Vt102Emulation::clearScreenAndSetColumns(int columnCount) -{ - setImageSize(_currentScreen->getLines(),columnCount); +void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { + setImageSize(_currentScreen->getLines(), columnCount); clearEntireScreen(); setDefaultMargins(); - _currentScreen->setCursorYX(0,0); + _currentScreen->setCursorYX(0, 0); } -void Vt102Emulation::sendString(const char* s , int length) -{ - if ( length >= 0 ) - emit sendData(s,length); - else - emit sendData(s,strlen(s)); +void Vt102Emulation::sendString(const char *s, int length) { + if (length >= 0) + emit sendData(s, length); + else + emit sendData(s, strlen(s)); } -void Vt102Emulation::reportCursorPosition() -{ - const size_t sz = 20; - char tmp[sz]; - const size_t r = snprintf(tmp, sz, "\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); - if (sz <= r) { - qWarning("Vt102Emulation::reportCursorPosition: Buffer too small\n"); - } - sendString(tmp); +void Vt102Emulation::reportCursorPosition() { + const size_t sz = 20; + char tmp[sz]; + const size_t r = + snprintf(tmp, sz, "\033[%d;%dR", _currentScreen->getCursorY() + 1, + _currentScreen->getCursorX() + 1); + if (sz <= r) { + qWarning("Vt102Emulation::reportCursorPosition: Buffer too small\n"); + } + sendString(tmp); } -void Vt102Emulation::reportTerminalType() -{ - // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) - // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) - // VT100: ^[[?1;2c - // VT101: ^[[?1;0c - // VT102: ^[[?6v - if (getMode(MODE_Ansi)) - sendString("\033[?1;2c"); // I'm a VT100 - else - sendString("\033/Z"); // I'm a VT52 +void Vt102Emulation::reportTerminalType() { + // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 + // Users Guide)) VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. + // capabilities) VT100: ^[[?1;2c VT101: ^[[?1;0c VT102: ^[[?6v + if (getMode(MODE_Ansi)) + sendString("\033[?1;2c"); // I'm a VT100 + else + sendString("\033/Z"); // I'm a VT52 } -void Vt102Emulation::reportSecondaryAttributes() -{ - // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) - if (getMode(MODE_Ansi)) - sendString("\033[>0;115;0c"); // Why 115? ;) - else - sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for - // konsoles backward compatibility. +void Vt102Emulation::reportSecondaryAttributes() { + // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) + if (getMode(MODE_Ansi)) + sendString("\033[>0;115;0c"); // Why 115? ;) + else + sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept + // for konsoles backward compatibility. } void Vt102Emulation::reportTerminalParms(int p) // DECREPTPARM { - const size_t sz = 100; - char tmp[sz]; - const size_t r = snprintf(tmp, sz, "\033[%d;1;1;112;112;1;0x",p); // not really true. - if (sz <= r) { - qWarning("Vt102Emulation::reportTerminalParms: Buffer too small\n"); - } - sendString(tmp); + const size_t sz = 100; + char tmp[sz]; + const size_t r = + snprintf(tmp, sz, "\033[%d;1;1;112;112;1;0x", p); // not really true. + if (sz <= r) { + qWarning("Vt102Emulation::reportTerminalParms: Buffer too small\n"); + } + sendString(tmp); } -void Vt102Emulation::reportStatus() -{ - sendString("\033[0n"); //VT100. Device status report. 0 = Ready. +void Vt102Emulation::reportStatus() { + sendString("\033[0n"); // VT100. Device status report. 0 = Ready. } -void Vt102Emulation::reportAnswerBack() -{ - // FIXME - Test this with VTTEST - // This is really obsolete VT100 stuff. - const char* ANSWER_BACK = ""; - sendString(ANSWER_BACK); +void Vt102Emulation::reportAnswerBack() { + // FIXME - Test this with VTTEST + // This is really obsolete VT100 stuff. + const char *ANSWER_BACK = ""; + sendString(ANSWER_BACK); } /*! - `cx',`cy' are 1-based. - `cb' indicates the button pressed or released (0-2) or scroll event (4-5). + `cx',`cy' are 1-based. + `cb' indicates the button pressed or released (0-2) or scroll event (4-5). - eventType represents the kind of mouse action that occurred: - 0 = Mouse button press - 1 = Mouse drag - 2 = Mouse button release + eventType represents the kind of mouse action that occurred: + 0 = Mouse button press + 1 = Mouse drag + 2 = Mouse button release */ -void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) -{ +void Vt102Emulation::sendMouseEvent(int cb, int cx, int cy, int eventType) { if (cx < 1 || cy < 1) - return; + return; // With the exception of the 1006 mode, button release is encoded in cb. - // Note that if multiple extensions are enabled, the 1006 is used, so it's okay to check for only that. + // Note that if multiple extensions are enabled, the 1006 is used, so it's + // okay to check for only that. if (eventType == 2 && !getMode(MODE_Mouse1006)) cb = 3; // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button if (cb >= 4) - cb += 0x3c; + cb += 0x3c; - //Mouse motion handling + // Mouse motion handling if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) - cb += 0x20; //add 32 to signify motion event + cb += 0x20; // add 32 to signify motion event char command[64]; command[0] = '\0'; - // Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. + // Check the extensions in decreasing order of preference. Encoding the + // release event above assumes that 1006 comes first. if (getMode(MODE_Mouse1006)) { - snprintf(command, sizeof(command), "\033[<%d;%d;%d%c", cb, cx, cy, eventType == 2 ? 'm' : 'M'); + snprintf(command, sizeof(command), "\033[<%d;%d;%d%c", cb, cx, cy, + eventType == 2 ? 'm' : 'M'); } else if (getMode(MODE_Mouse1015)) { snprintf(command, sizeof(command), "\033[%d;%d;%dM", cb + 0x20, cx, cy); } else if (getMode(MODE_Mouse1005)) { @@ -1076,13 +1631,15 @@ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) coords[1] = static_cast(cy + 0x20); QString coordsStr = QString(coords, 2); QByteArray utf8 = coordsStr.toUtf8(); - snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, utf8.constData()); + snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, + utf8.constData()); } } else if (cx <= 223 && cy <= 223) { - snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, cy + 0x20); + snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, + cy + 0x20); } - sendString(command); + sendString(command); } /** @@ -1092,8 +1649,7 @@ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusLost autocmd: https://github.com/sjl/vitality.vim */ -void Vt102Emulation::focusLost(void) -{ +void Vt102Emulation::focusLost(void) { if (_reportFocusEvents) sendString("\033[O"); } @@ -1105,39 +1661,35 @@ void Vt102Emulation::focusLost(void) * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusGained autocmd: https://github.com/sjl/vitality.vim */ -void Vt102Emulation::focusGained(void) -{ +void Vt102Emulation::focusGained(void) { if (_reportFocusEvents) sendString("\033[I"); } -void Vt102Emulation::sendText( const QString& text ) -{ - if (!text.isEmpty()) - { - QKeyEvent event(QEvent::KeyPress, - 0, - Qt::NoModifier, - text); - sendKeyEvent(&event, false); // expose as a big fat keypress event - } +void Vt102Emulation::sendText(const QString &text) { + if (!text.isEmpty()) { + QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); + sendKeyEvent(&event, false); // expose as a big fat keypress event + } } -void Vt102Emulation::sendKeyEvent(QKeyEvent* event, bool fromPaste) -{ +void Vt102Emulation::sendKeyEvent(QKeyEvent *event, bool fromPaste) { Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states - if (getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; - if (getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; - if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; - if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; + if (getMode(MODE_NewLine)) + states |= KeyboardTranslator::NewLineState; + if (getMode(MODE_Ansi)) + states |= KeyboardTranslator::AnsiState; + if (getMode(MODE_AppCuKeys)) + states |= KeyboardTranslator::CursorKeysState; + if (getMode(MODE_AppScreen)) + states |= KeyboardTranslator::AlternateScreenState; if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) states |= KeyboardTranslator::ApplicationKeypadState; // check flow control state - if (modifiers & KeyboardTranslator::CTRL_MOD) - { + if (modifiers & KeyboardTranslator::CTRL_MOD) { switch (event->key()) { case Qt::Key_S: emit flowControlKeyPressed(true); @@ -1150,35 +1702,35 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent* event, bool fromPaste) } // lookup key binding - if ( _keyTranslator ) - { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - event->key() , - modifiers, - states ); + if (_keyTranslator) { + KeyboardTranslator::Entry entry = + _keyTranslator->findEntry(event->key(), modifiers, states); if ((modifiers & Qt::AltModifier) && (event->key() == Qt::Key_Left)) { entry = _keyTranslator->findEntry(Qt::Key_Home, Qt::NoModifier, states); modifiers = Qt::NoModifier; - } else if ((modifiers & Qt::AltModifier) && (event->key() == Qt::Key_Right)) { + } else if ((modifiers & Qt::AltModifier) && + (event->key() == Qt::Key_Right)) { entry = _keyTranslator->findEntry(Qt::Key_End, Qt::NoModifier, states); modifiers = Qt::NoModifier; - } - #if defined(Q_OS_MACOS) - if (( modifiers & Qt::ControlModifier ) && ( event->key() == Qt::Key_Backspace )) { + } +#if defined(Q_OS_MACOS) + if ((modifiers & Qt::ControlModifier) && + (event->key() == Qt::Key_Backspace)) { entry = _keyTranslator->findEntry(Qt::Key_Delete, Qt::NoModifier, states); modifiers = Qt::NoModifier; } - #endif - #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) - if (_enableHandleCtrlC && ( modifiers & Qt::ControlModifier ) && ( event->key() == Qt::Key_C )){ +#endif +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) + if (_enableHandleCtrlC && (modifiers & Qt::ControlModifier) && + (event->key() == Qt::Key_C)) { bool isSelection = !_currentScreen->isClearSelection(); if (isSelection) { emit handleCtrlC(); return; } } - #endif +#endif // send result to terminal QByteArray textToSend; @@ -1187,67 +1739,59 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent* event, bool fromPaste) // Alt+[Character] results in Esc+[Character] being sent // (unless there is an entry defined for this particular combination // in the keyboard modifier) - bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; - bool wantsMetaModifier = entry.modifiers() & entry.modifierMask() & Qt::MetaModifier; - bool wantsAnyModifier = entry.state() & - entry.stateMask() & KeyboardTranslator::AnyModifierState; - - if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) - && !event->text().isEmpty() ) - { + bool wantsAltModifier = + entry.modifiers() & entry.modifierMask() & Qt::AltModifier; + bool wantsMetaModifier = + entry.modifiers() & entry.modifierMask() & Qt::MetaModifier; + bool wantsAnyModifier = entry.state() & entry.stateMask() & + KeyboardTranslator::AnyModifierState; + + if (modifiers & Qt::AltModifier && + !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty()) { textToSend.prepend("\033"); } - if ( modifiers & Qt::MetaModifier && !(wantsMetaModifier || wantsAnyModifier) - && !event->text().isEmpty() ) - { + if (modifiers & Qt::MetaModifier && + !(wantsMetaModifier || wantsAnyModifier) && !event->text().isEmpty()) { textToSend.prepend("\030@s"); } - if ( entry.command() != KeyboardTranslator::NoCommand ) - { + if (entry.command() != KeyboardTranslator::NoCommand) { if (entry.command() & KeyboardTranslator::EraseCommand) { textToSend += eraseChar(); } else { - Q_EMIT handleCommandFromKeyboard(entry.command()); + emit handleCommandFromKeyboard(entry.command()); } // TODO command handling - } - else if ( !entry.text().isEmpty() ) - { + } else if (!entry.text().isEmpty()) { textToSend += entry.text(true, modifiers); - } - else if((modifiers & KeyboardTranslator::CTRL_MOD) && event->key() >= 0x40 && event->key() < 0x5f) { + } else if ((modifiers & KeyboardTranslator::CTRL_MOD) && + event->key() >= 0x40 && event->key() < 0x5f) { textToSend += (event->key() & 0x1f); - } - else if(event->key() == Qt::Key_Tab) { + } else if (event->key() == Qt::Key_Tab) { textToSend += 0x09; - } - else if (event->key() == Qt::Key_PageUp) { + } else if (event->key() == Qt::Key_PageUp) { textToSend += "\033[5~"; - } - else if (event->key() == Qt::Key_PageDown) { + } else if (event->key() == Qt::Key_PageDown) { textToSend += "\033[6~"; - } - else { + } else { textToSend += _fromUtf16(event->text()); } if (!fromPaste && textToSend.length()) { - Q_EMIT outputFromKeypressEvent(); + emit outputFromKeypressEvent(); } - Q_EMIT sendData( textToSend.constData() , textToSend.length() ); - } - else - { + emit sendData(textToSend.constData(), textToSend.length()); + } else { // print an error message to the terminal if no key translator has been // set - QString translatorError = tr("No keyboard translator available. " - "The information needed to convert key presses " - "into characters to send to the terminal " - "is missing."); + QString translatorError = + tr("No keyboard translator available. " + "The information needed to convert key presses " + "into characters to send to the terminal " + "is missing."); reset(); - receiveData( translatorError.toUtf8().constData() , translatorError.size() ); + receiveData(translatorError.toUtf8().constData(), translatorError.size()); } } @@ -1260,96 +1804,99 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent* event, bool fromPaste) // Character Set Conversion ------------------------------------------------ -- /* - The processing contains a VT100 specific code translation layer. - It's still in use and mainly responsible for the line drawing graphics. - - These and some other glyphs are assigned to codes (0x5f-0xfe) - normally occupied by the latin letters. Since this codes also - appear within control sequences, the extra code conversion - does not permute with the tokenizer and is placed behind it - in the pipeline. It only applies to tokens, which represent - plain characters. - - This conversion it eventually continued in TerminalDisplay.C, since - it might involve VT100 enhanced fonts, which have these - particular glyphs allocated in (0x00-0x1f) in their code page. + The processing contains a VT100 specific code translation layer. + It's still in use and mainly responsible for the line drawing graphics. + + These and some other glyphs are assigned to codes (0x5f-0xfe) + normally occupied by the latin letters. Since this codes also + appear within control sequences, the extra code conversion + does not permute with the tokenizer and is placed behind it + in the pipeline. It only applies to tokens, which represent + plain characters. + + This conversion it eventually continued in TerminalDisplay.C, since + it might involve VT100 enhanced fonts, which have these + particular glyphs allocated in (0x00-0x1f) in their code page. */ -#define CHARSET _charset[_currentScreen==_screen[1]] +#define CHARSET _charset[_currentScreen == _screen[1]] // Apply current character map. -wchar_t Vt102Emulation::applyCharset(wchar_t c) -{ - if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; - if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete - return c; +wchar_t Vt102Emulation::applyCharset(wchar_t c) { + // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. + const unsigned short vt100_graphics[32] = { + // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 + 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, + 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, + 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, + 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7}; + if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) + return vt100_graphics[c - 0x5f]; + if (CHARSET.pound && c == '#') + return 0xa3; // This mode is obsolete + return c; } /* - "Charset" related part of the emulation state. - This configures the VT100 charset filter. + "Charset" related part of the emulation state. + This configures the VT100 charset filter. - While most operation work on the current _screen, - the following two are different. + While most operation work on the current _screen, + the following two are different. */ -void Vt102Emulation::resetCharset(int scrno) -{ - _charset[scrno].cu_cs = 0; - qstrncpy(_charset[scrno].charset,"BBBB",4); - _charset[scrno].sa_graphic = false; - _charset[scrno].sa_pound = false; - _charset[scrno].graphic = false; - _charset[scrno].pound = false; +void Vt102Emulation::resetCharset(int scrno) { + _charset[scrno].cu_cs = 0; + qstrncpy(_charset[scrno].charset, "BBBB", 4); + _charset[scrno].sa_graphic = false; + _charset[scrno].sa_pound = false; + _charset[scrno].graphic = false; + _charset[scrno].pound = false; } void Vt102Emulation::setCharset(int n, int cs) // on both screens. { - _charset[0].charset[n&3] = cs; useCharset(_charset[0].cu_cs); - _charset[1].charset[n&3] = cs; useCharset(_charset[1].cu_cs); + _charset[0].charset[n & 3] = cs; + useCharset(_charset[0].cu_cs); + _charset[1].charset[n & 3] = cs; + useCharset(_charset[1].cu_cs); } -void Vt102Emulation::setAndUseCharset(int n, int cs) -{ - CHARSET.charset[n&3] = cs; - useCharset(n&3); +void Vt102Emulation::setAndUseCharset(int n, int cs) { + CHARSET.charset[n & 3] = cs; + useCharset(n & 3); } -void Vt102Emulation::useCharset(int n) -{ - CHARSET.cu_cs = n&3; - CHARSET.graphic = (CHARSET.charset[n&3] == '0'); - CHARSET.pound = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete +void Vt102Emulation::useCharset(int n) { + CHARSET.cu_cs = n & 3; + CHARSET.graphic = (CHARSET.charset[n & 3] == '0'); + CHARSET.pound = (CHARSET.charset[n & 3] == 'A'); // This mode is obsolete } -void Vt102Emulation::setDefaultMargins() -{ +void Vt102Emulation::setDefaultMargins() { _screen[0]->setDefaultMargins(); _screen[1]->setDefaultMargins(); } -void Vt102Emulation::setMargins(int t, int b) -{ - _screen[0]->setMargins(t, b); - _screen[1]->setMargins(t, b); +void Vt102Emulation::setMargins(int t, int b) { + _screen[0]->setMargins(t, b); + _screen[1]->setMargins(t, b); } -void Vt102Emulation::saveCursor() -{ - CHARSET.sa_graphic = CHARSET.graphic; - CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete - // we are not clear about these - //sa_charset = charsets[cScreen->_charset]; - //sa_charset_num = cScreen->_charset; - _currentScreen->saveCursor(); +void Vt102Emulation::saveCursor() { + CHARSET.sa_graphic = CHARSET.graphic; + CHARSET.sa_pound = CHARSET.pound; // This mode is obsolete + // we are not clear about these + // sa_charset = charsets[cScreen->_charset]; + // sa_charset_num = cScreen->_charset; + _currentScreen->saveCursor(); } -void Vt102Emulation::restoreCursor() -{ - CHARSET.graphic = CHARSET.sa_graphic; - CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete - _currentScreen->restoreCursor(); +void Vt102Emulation::restoreCursor() { + CHARSET.graphic = CHARSET.sa_graphic; + CHARSET.pound = CHARSET.sa_pound; // This mode is obsolete + _currentScreen->restoreCursor(); } /* ------------------------------------------------------------------------- */ @@ -1359,46 +1906,55 @@ void Vt102Emulation::restoreCursor() /* ------------------------------------------------------------------------- */ /* - Some of the emulations state is either added to the state of the screens. + Some of the emulations state is either added to the state of the screens. - This causes some scoping problems, since different emulations choose to - located the mode either to the current _screen or to both. + This causes some scoping problems, since different emulations choose to + located the mode either to the current _screen or to both. - For strange reasons, the extend of the rendition attributes ranges over - all screens and not over the actual _screen. + For strange reasons, the extend of the rendition attributes ranges over + all screens and not over the actual _screen. - We decided on the precise precise extend, somehow. + We decided on the precise precise extend, somehow. */ // "Mode" related part of the state. These are all booleans. -void Vt102Emulation::resetModes() -{ - // MODE_Allow132Columns is not reset here - // to match Xterm's behaviour (see Xterm's VTReset() function) - - resetMode(MODE_132Columns); saveMode(MODE_132Columns); - resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); - resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); - resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); - resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); - resetMode(MODE_Mouse1005); saveMode(MODE_Mouse1005); - resetMode(MODE_Mouse1006); saveMode(MODE_Mouse1006); - resetMode(MODE_Mouse1015); saveMode(MODE_Mouse1015); - resetMode(MODE_BracketedPaste); saveMode(MODE_BracketedPaste); - - resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); - resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); - resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); - resetMode(MODE_NewLine); - setMode(MODE_Ansi); +void Vt102Emulation::resetModes() { + // MODE_Allow132Columns is not reset here + // to match Xterm's behaviour (see Xterm's VTReset() function) + + resetMode(MODE_132Columns); + saveMode(MODE_132Columns); + resetMode(MODE_Mouse1000); + saveMode(MODE_Mouse1000); + resetMode(MODE_Mouse1001); + saveMode(MODE_Mouse1001); + resetMode(MODE_Mouse1002); + saveMode(MODE_Mouse1002); + resetMode(MODE_Mouse1003); + saveMode(MODE_Mouse1003); + resetMode(MODE_Mouse1005); + saveMode(MODE_Mouse1005); + resetMode(MODE_Mouse1006); + saveMode(MODE_Mouse1006); + resetMode(MODE_Mouse1015); + saveMode(MODE_Mouse1015); + resetMode(MODE_BracketedPaste); + saveMode(MODE_BracketedPaste); + + resetMode(MODE_AppScreen); + saveMode(MODE_AppScreen); + resetMode(MODE_AppCuKeys); + saveMode(MODE_AppCuKeys); + resetMode(MODE_AppKeyPad); + saveMode(MODE_AppKeyPad); + resetMode(MODE_NewLine); + setMode(MODE_Ansi); } -void Vt102Emulation::setMode(int m) -{ - _currentModes.mode[m] = true; - switch (m) - { +void Vt102Emulation::setMode(int m) { + _currentModes.mode[m] = true; + switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(132); @@ -1410,89 +1966,79 @@ void Vt102Emulation::setMode(int m) case MODE_Mouse1002: case MODE_Mouse1003: emit programUsesMouseChanged(false); - break; + break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(true); - break; - - case MODE_AppScreen : _screen[1]->clearSelection(); - setScreen(1); - break; - } - if (m < MODES_SCREEN || m == MODE_NewLine) - { - _screen[0]->setMode(m); - _screen[1]->setMode(m); - } + break; + + case MODE_AppScreen: + _screen[1]->clearSelection(); + setScreen(1); + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) { + _screen[0]->setMode(m); + _screen[1]->setMode(m); + } } -void Vt102Emulation::resetMode(int m) -{ - _currentModes.mode[m] = false; - switch (m) - { +void Vt102Emulation::resetMode(int m) { + _currentModes.mode[m] = false; + switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(80); break; - case MODE_Mouse1000 : - case MODE_Mouse1001 : - case MODE_Mouse1002 : - case MODE_Mouse1003 : + case MODE_Mouse1000: + case MODE_Mouse1001: + case MODE_Mouse1002: + case MODE_Mouse1003: emit programUsesMouseChanged(true); - break; + break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(false); - break; + break; - case MODE_AppScreen : + case MODE_AppScreen: _screen[0]->clearSelection(); setScreen(0); - break; - } - if (m < MODES_SCREEN || m == MODE_NewLine) - { - _screen[0]->resetMode(m); - _screen[1]->resetMode(m); - } + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) { + _screen[0]->resetMode(m); + _screen[1]->resetMode(m); + } } -void Vt102Emulation::saveMode(int m) -{ - _savedModes.mode[m] = _currentModes.mode[m]; +void Vt102Emulation::saveMode(int m) { + _savedModes.mode[m] = _currentModes.mode[m]; } -void Vt102Emulation::restoreMode(int m) -{ - if (_savedModes.mode[m]) - setMode(m); - else - resetMode(m); +void Vt102Emulation::restoreMode(int m) { + if (_savedModes.mode[m]) + setMode(m); + else + resetMode(m); } -bool Vt102Emulation::getMode(int m) -{ - return _currentModes.mode[m]; -} +bool Vt102Emulation::getMode(int m) { return _currentModes.mode[m]; } -char Vt102Emulation::eraseChar() const -{ - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - Qt::Key_Backspace, - Qt::NoModifier, - KeyboardTranslator::NoState); - if ( entry.text().size() > 0 ) - return entry.text().at(0); - else - return '\b'; +char Vt102Emulation::eraseChar() const { + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + Qt::Key_Backspace, Qt::NoModifier, KeyboardTranslator::NoState); + if (entry.text().size() > 0) + return entry.text().at(0); + else + return '\b'; } -void Vt102Emulation::reportDecodingError() -{ - if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) - return; - qCDebug(qtermwidgetLogger) << "Undecodable sequence:" << QString::fromWCharArray(tokenBuffer, tokenBufferPos); +void Vt102Emulation::reportDecodingError() { + if (tokenBufferPos == 0 || + (tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32)) + return; + qCDebug(qtermwidgetLogger) + << "Undecodable sequence:" + << QString::fromWCharArray(tokenBuffer, tokenBufferPos); } - diff --git a/lib/qtermwidget/qtermwidget.cpp b/lib/qtermwidget/qtermwidget.cpp index 814ca248..7461db58 100644 --- a/lib/qtermwidget/qtermwidget.cpp +++ b/lib/qtermwidget/qtermwidget.cpp @@ -1,19 +1,20 @@ -/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 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 - Library 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. +/* + Copyright (C) 2008 e_k (e_k@users.sourceforge.net) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 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 + Library 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 #include @@ -43,8 +44,7 @@ #define STEP_ZOOM 3 QTermWidget::QTermWidget(QWidget *messageParentWidget, QWidget *parent) - : QWidget(parent) -{ + : QWidget(parent) { m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0, 0, 0, 0); setLayout(m_layout); @@ -163,8 +163,7 @@ QTermWidget::QTermWidget(QWidget *messageParentWidget, QWidget *parent) }); } -QTermWidget::~QTermWidget() -{ +QTermWidget::~QTermWidget() { setUrlFilterEnabled(false); clearHighLightTexts(); delete m_urlFilter; @@ -173,22 +172,19 @@ QTermWidget::~QTermWidget() delete m_emulation; } -void QTermWidget::selectionChanged(bool textSelected) -{ +void QTermWidget::selectionChanged(bool textSelected) { emit copyAvailable(textSelected); } -void QTermWidget::search(bool forwards, bool next) -{ +void QTermWidget::search(bool forwards, bool next) { int startColumn, startLine; - if (next) // search from just after current selection - { + if (next) { + // search from just after current selection m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); startColumn++; - } - else // search from start of current selection - { + } else { + // search from start of current selection m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine); } @@ -221,93 +217,74 @@ void QTermWidget::search(bool forwards, bool next) historySearch->search(); } -QSize QTermWidget::sizeHint() const -{ +QSize QTermWidget::sizeHint() const { QSize size = m_terminalDisplay->sizeHint(); size.rheight() = 150; return size; } -void QTermWidget::setTerminalSizeHint(bool enabled) -{ +void QTermWidget::setTerminalSizeHint(bool enabled) { m_terminalDisplay->setTerminalSizeHint(enabled); } -bool QTermWidget::terminalSizeHint() -{ +bool QTermWidget::terminalSizeHint() { return m_terminalDisplay->terminalSizeHint(); } -void QTermWidget::setTerminalFont(const QFont &font) -{ +void QTermWidget::setTerminalFont(const QFont &font) { m_terminalDisplay->setVTFont(font); } -QFont QTermWidget::getTerminalFont() -{ +QFont QTermWidget::getTerminalFont() { return m_terminalDisplay->getVTFont(); } -void QTermWidget::setTerminalOpacity(qreal level) -{ +void QTermWidget::setTerminalOpacity(qreal level) { m_terminalDisplay->setOpacity(level); } -void QTermWidget::setTerminalBackgroundImage(const QString& backgroundImage) -{ +void QTermWidget::setTerminalBackgroundImage(const QString& backgroundImage) { m_terminalDisplay->setBackgroundImage(backgroundImage); } -void QTermWidget::setTerminalBackgroundMovie(const QString& backgroundMovie) -{ +void QTermWidget::setTerminalBackgroundMovie(const QString& backgroundMovie) { m_terminalDisplay->setBackgroundMovie(backgroundMovie); } -void QTermWidget::setTerminalBackgroundVideo(const QString& backgroundVideo) -{ +void QTermWidget::setTerminalBackgroundVideo(const QString& backgroundVideo) { m_terminalDisplay->setBackgroundVideo(backgroundVideo); } -void QTermWidget::setTerminalBackgroundMode(int mode) -{ +void QTermWidget::setTerminalBackgroundMode(int mode) { m_terminalDisplay->setBackgroundMode((BackgroundMode)mode); } -void QTermWidget::setTextCodec(QStringEncoder codec) -{ +void QTermWidget::setTextCodec(QStringEncoder codec) { m_emulation->setCodec(std::move(codec)); } -void QTermWidget::setColorScheme(const QString& origName) -{ +void QTermWidget::setColorScheme(const QString& origName) { const ColorScheme *cs = nullptr; const bool isFile = QFile::exists(origName); - const QString& name = isFile ? - QFileInfo(origName).baseName() : - origName; + const QString& name = isFile ? QFileInfo(origName).baseName() : origName; // avoid legacy (int) solution - if (!availableColorSchemes().contains(name)) - { - if (isFile) - { + if (!availableColorSchemes().contains(name)) { + if (isFile) { if (ColorSchemeManager::instance()->loadCustomColorScheme(origName)) cs = ColorSchemeManager::instance()->findColorScheme(name); else - qWarning () << Q_FUNC_INFO - << "cannot load color scheme from" - << origName; + qWarning () << Q_FUNC_INFO << "cannot load color scheme from" << origName; } if (!cs) cs = ColorSchemeManager::instance()->defaultColorScheme(); - } - else + } else { cs = ColorSchemeManager::instance()->findColorScheme(name); + } - if (! cs) - { + if (! cs) { QMessageBox::information(messageParentWidget, tr("Color Scheme Error"), tr("Cannot load color scheme: %1").arg(name)); @@ -319,13 +296,11 @@ void QTermWidget::setColorScheme(const QString& origName) m_hasDarkBackground = cs->hasDarkBackground(); } -QStringList QTermWidget::getAvailableColorSchemes() -{ +QStringList QTermWidget::getAvailableColorSchemes() { return QTermWidget::availableColorSchemes(); } -QStringList QTermWidget::availableColorSchemes() -{ +QStringList QTermWidget::availableColorSchemes() { QStringList ret; const auto allColorSchemes = ColorSchemeManager::instance()->allColorSchemes(); for (const ColorScheme* cs : allColorSchemes) @@ -333,38 +308,31 @@ QStringList QTermWidget::availableColorSchemes() return ret; } -void QTermWidget::addCustomColorSchemeDir(const QString& custom_dir) -{ +void QTermWidget::addCustomColorSchemeDir(const QString& custom_dir) { ColorSchemeManager::instance()->addCustomColorSchemeDir(custom_dir); } -void QTermWidget::setBackgroundColor(const QColor &color) -{ +void QTermWidget::setBackgroundColor(const QColor &color) { m_terminalDisplay->setBackgroundColor(color); } -void QTermWidget::setForegroundColor(const QColor &color) -{ +void QTermWidget::setForegroundColor(const QColor &color) { m_terminalDisplay->setForegroundColor(color); } -void QTermWidget::setANSIColor(const int ansiColorId, const QColor &color) -{ +void QTermWidget::setANSIColor(const int ansiColorId, const QColor &color) { m_terminalDisplay->setColorTableColor(ansiColorId, color); } -void QTermWidget::setPreeditColorIndex(int index) -{ +void QTermWidget::setPreeditColorIndex(int index) { m_terminalDisplay->setPreeditColorIndex(index); } -void QTermWidget::setSize(const QSize &size) -{ +void QTermWidget::setSize(const QSize &size) { m_terminalDisplay->setSize(size.width(), size.height()); } -void QTermWidget::setHistorySize(int lines) -{ +void QTermWidget::setHistorySize(int lines) { if (lines < 0) m_emulation->setHistory(HistoryTypeFile()); else if (lines == 0) @@ -373,8 +341,7 @@ void QTermWidget::setHistorySize(int lines) m_emulation->setHistory(HistoryTypeBuffer(lines)); } -int QTermWidget::historySize() const -{ +int QTermWidget::historySize() const { const HistoryType& currentHistory = m_emulation->history(); if (currentHistory.isEnabled()) { @@ -388,39 +355,32 @@ int QTermWidget::historySize() const } } -void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) -{ +void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) { m_terminalDisplay->setScrollBarPosition(pos); } -void QTermWidget::scrollToEnd() -{ +void QTermWidget::scrollToEnd() { m_terminalDisplay->scrollToEnd(); } -void QTermWidget::sendText(const QString &text) -{ +void QTermWidget::sendText(const QString &text) { m_emulation->sendText(text); } -void QTermWidget::sendKeyEvent(QKeyEvent *e) -{ +void QTermWidget::sendKeyEvent(QKeyEvent *e) { m_emulation->sendKeyEvent(e, false); } -void QTermWidget::resizeEvent(QResizeEvent*) -{ +void QTermWidget::resizeEvent(QResizeEvent*) { //qDebug("global window resizing...with %d %d", this->size().width(), this->size().height()); m_terminalDisplay->resize(this->size()); } -void QTermWidget::sessionFinished() -{ +void QTermWidget::sessionFinished() { emit finished(); } -void QTermWidget::updateTerminalSize() -{ +void QTermWidget::updateTerminalSize() { int minLines = -1; int minColumns = -1; @@ -444,8 +404,7 @@ void QTermWidget::updateTerminalSize() } } -void QTermWidget::monitorTimerDone() -{ +void QTermWidget::monitorTimerDone() { //FIXME: The idea here is that the notification popup will appear to tell the user than output from //the terminal has stopped and the popup will disappear when the user activates the session. // @@ -464,8 +423,7 @@ void QTermWidget::monitorTimerDone() m_notifiedActivity=false; } -void QTermWidget::activityStateSet(int state) -{ +void QTermWidget::activityStateSet(int state) { if (state==NOTIFYBELL) { m_terminalDisplay->bell("Bell in QTermWidget!"); } else if (state==NOTIFYACTIVITY) { @@ -492,16 +450,14 @@ void QTermWidget::activityStateSet(int state) emit stateChanged(state); } -void QTermWidget::setMonitorActivity(bool enabled) -{ +void QTermWidget::setMonitorActivity(bool enabled) { m_monitorActivity=enabled; m_notifiedActivity=false; activityStateSet(NOTIFYNORMAL); } -void QTermWidget::setMonitorSilence(bool enabled) -{ +void QTermWidget::setMonitorSilence(bool enabled) { if (m_monitorSilence==enabled) { return; } @@ -516,56 +472,46 @@ void QTermWidget::setMonitorSilence(bool enabled) activityStateSet(NOTIFYNORMAL); } -void QTermWidget::setSilenceTimeout(int seconds) -{ +void QTermWidget::setSilenceTimeout(int seconds) { m_silenceSeconds=seconds; if (m_monitorSilence) { m_monitorTimer->start(m_silenceSeconds*1000); } } -void QTermWidget::bracketText(QString& text) -{ +void QTermWidget::bracketText(QString& text) { m_terminalDisplay->bracketText(text); } -void QTermWidget::disableBracketedPasteMode(bool disable) -{ +void QTermWidget::disableBracketedPasteMode(bool disable) { m_terminalDisplay->disableBracketedPasteMode(disable); } -bool QTermWidget::bracketedPasteModeIsDisabled() const -{ +bool QTermWidget::bracketedPasteModeIsDisabled() const { return m_terminalDisplay->bracketedPasteModeIsDisabled(); } -void QTermWidget::copyClipboard() -{ +void QTermWidget::copyClipboard() { m_terminalDisplay->copyClipboard(QClipboard::Clipboard); } -void QTermWidget::copySelection() -{ +void QTermWidget::copySelection() { m_terminalDisplay->copyClipboard(QClipboard::Selection); } -void QTermWidget::pasteClipboard() -{ +void QTermWidget::pasteClipboard() { m_terminalDisplay->pasteClipboard(); } -void QTermWidget::pasteSelection() -{ +void QTermWidget::pasteSelection() { m_terminalDisplay->pasteSelection(); } -void QTermWidget::selectAll() -{ +void QTermWidget::selectAll() { m_terminalDisplay->selectAll(); } -int QTermWidget::setZoom(int step) -{ +int QTermWidget::setZoom(int step) { QFont font = m_terminalDisplay->getVTFont(); font.setPointSize(font.pointSize() + step); @@ -573,34 +519,28 @@ int QTermWidget::setZoom(int step) return font.pointSize(); } -int QTermWidget::zoomIn() -{ +int QTermWidget::zoomIn() { return setZoom(STEP_ZOOM); } -int QTermWidget::zoomOut() -{ +int QTermWidget::zoomOut() { return setZoom(-STEP_ZOOM); } -void QTermWidget::setKeyBindings(const QString & kb) -{ +void QTermWidget::setKeyBindings(const QString & kb) { m_emulation->setKeyBindings(kb); } -void QTermWidget::clear() -{ +void QTermWidget::clear() { clearScreen(); clearScrollback(); } -void QTermWidget::clearScrollback() -{ +void QTermWidget::clearScrollback() { m_emulation->clearHistory(); } -void QTermWidget::clearScreen() -{ +void QTermWidget::clearScreen() { m_emulation->reset(); /** * TODO: @@ -610,8 +550,7 @@ void QTermWidget::clearScreen() */ } -void QTermWidget::setFlowControlEnabled(bool enabled) -{ +void QTermWidget::setFlowControlEnabled(bool enabled) { if (m_flowControl == enabled) { return; } @@ -621,31 +560,26 @@ void QTermWidget::setFlowControlEnabled(bool enabled) emit flowControlEnabledChanged(enabled); } -bool QTermWidget::flowControlEnabled(void) -{ +bool QTermWidget::flowControlEnabled(void) { return m_flowControl; } -void QTermWidget::setFlowControlWarningEnabled(bool enabled) -{ +void QTermWidget::setFlowControlWarningEnabled(bool enabled) { if (flowControlEnabled()) { // Do not show warning label if flow control is disabled m_terminalDisplay->setFlowControlWarningEnabled(enabled); } } -QStringList QTermWidget::availableKeyBindings() -{ +QStringList QTermWidget::availableKeyBindings() { return KeyboardTranslatorManager::instance()->allTranslators(); } -QString QTermWidget::keyBindings() -{ +QString QTermWidget::keyBindings() { return m_emulation->keyBindings(); } -void QTermWidget::toggleShowSearchBar() -{ +void QTermWidget::toggleShowSearchBar() { if(m_searchBar->isHidden()) { m_searchBar->setText(selectedText(true)); m_searchBar->show(); @@ -654,118 +588,96 @@ void QTermWidget::toggleShowSearchBar() } } -void QTermWidget::setMotionAfterPasting(int action) -{ +void QTermWidget::setMotionAfterPasting(int action) { m_terminalDisplay->setMotionAfterPasting((MotionAfterPasting) action); } -int QTermWidget::historyLinesCount() -{ +int QTermWidget::historyLinesCount() { return m_terminalDisplay->screenWindow()->screen()->getHistLines(); } -int QTermWidget::screenColumnsCount() -{ +int QTermWidget::screenColumnsCount() { return m_terminalDisplay->screenWindow()->screen()->getColumns(); } -int QTermWidget::screenLinesCount() -{ +int QTermWidget::screenLinesCount() { return m_terminalDisplay->screenWindow()->screen()->getLines(); } -void QTermWidget::setSelectionStart(int row, int column) -{ +void QTermWidget::setSelectionStart(int row, int column) { m_terminalDisplay->screenWindow()->screen()->setSelectionStart(column, row, true); } -void QTermWidget::setSelectionEnd(int row, int column) -{ +void QTermWidget::setSelectionEnd(int row, int column) { m_terminalDisplay->screenWindow()->screen()->setSelectionEnd(column, row); } -void QTermWidget::getSelectionStart(int& row, int& column) -{ +void QTermWidget::getSelectionStart(int& row, int& column) { m_terminalDisplay->screenWindow()->screen()->getSelectionStart(column, row); } -void QTermWidget::getSelectionEnd(int& row, int& column) -{ +void QTermWidget::getSelectionEnd(int& row, int& column) { m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(column, row); } -QString QTermWidget::selectedText(bool preserveLineBreaks) -{ +QString QTermWidget::selectedText(bool preserveLineBreaks) { return m_terminalDisplay->screenWindow()->screen()->selectedText(preserveLineBreaks); } -Filter::HotSpot* QTermWidget::getHotSpotAt(const QPoint &pos) const -{ +Filter::HotSpot* QTermWidget::getHotSpotAt(const QPoint &pos) const { int row = 0, column = 0; m_terminalDisplay->getCharacterPosition(pos, row, column); return getHotSpotAt(row, column); } -Filter::HotSpot* QTermWidget::getHotSpotAt(int row, int column) const -{ +Filter::HotSpot* QTermWidget::getHotSpotAt(int row, int column) const { return m_terminalDisplay->filterChain()->hotSpotAt(row, column); } -QList QTermWidget::filterActions(const QPoint& position) -{ +QList QTermWidget::filterActions(const QPoint& position) { return m_terminalDisplay->filterActions(position); } -int QTermWidget::recvData(const char *buff, int len) const -{ +int QTermWidget::recvData(const char *buff, int len) const { m_emulation->receiveData( buff, len ); return len; } -void QTermWidget::setKeyboardCursorShape(KeyboardCursorShape shape) -{ +void QTermWidget::setKeyboardCursorShape(KeyboardCursorShape shape) { m_terminalDisplay->setKeyboardCursorShape(shape); } -void QTermWidget::setKeyboardCursorShape(uint32_t shape) -{ +void QTermWidget::setKeyboardCursorShape(uint32_t shape) { m_terminalDisplay->setKeyboardCursorShape((KeyboardCursorShape)shape); } -void QTermWidget::setBlinkingCursor(bool blink) -{ +void QTermWidget::setBlinkingCursor(bool blink) { m_terminalDisplay->setBlinkingCursor(blink); } -void QTermWidget::setBidiEnabled(bool enabled) -{ +void QTermWidget::setBidiEnabled(bool enabled) { m_terminalDisplay->setBidiEnabled(enabled); } -bool QTermWidget::isBidiEnabled() -{ +bool QTermWidget::isBidiEnabled() { return m_terminalDisplay->isBidiEnabled(); } -void QTermWidget::cursorChanged(Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) -{ +void QTermWidget::cursorChanged(Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { // TODO: A switch to enable/disable DECSCUSR? setKeyboardCursorShape(cursorShape); setBlinkingCursor(blinkingCursorEnabled); } -void QTermWidget::setMargin(int margin) -{ +void QTermWidget::setMargin(int margin) { m_terminalDisplay->setMargin(margin); } -int QTermWidget::getMargin() const -{ +int QTermWidget::getMargin() const { return m_terminalDisplay->margin(); } -void QTermWidget::saveHistory(QTextStream *stream, int format, int start, int end) -{ +void QTermWidget::saveHistory(QTextStream *stream, int format, int start, int end) { TerminalCharacterDecoder *decoder; if(format == 0) { decoder = new PlainTextDecoder; @@ -783,26 +695,22 @@ void QTermWidget::saveHistory(QTextStream *stream, int format, int start, int en delete decoder; } -void QTermWidget::saveHistory(QIODevice *device, int format, int start, int end) -{ +void QTermWidget::saveHistory(QIODevice *device, int format, int start, int end) { QTextStream stream(device); saveHistory(&stream, format, start, end); } -void QTermWidget::screenShot(QPixmap *pixmap) -{ +void QTermWidget::screenShot(QPixmap *pixmap) { QPixmap currPixmap(m_terminalDisplay->size()); m_terminalDisplay->render(&currPixmap); *pixmap = currPixmap.scaled(pixmap->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } -void QTermWidget::repaintDisplay(void) -{ +void QTermWidget::repaintDisplay(void) { m_terminalDisplay->repaintDisplay(); } -void QTermWidget::screenShot(const QString &fileName) -{ +void QTermWidget::screenShot(const QString &fileName) { qreal deviceratio = m_terminalDisplay->devicePixelRatio(); deviceratio = deviceratio*2; QPixmap pixmap(m_terminalDisplay->size() * deviceratio); @@ -811,19 +719,16 @@ void QTermWidget::screenShot(const QString &fileName) pixmap.save(fileName); } -void QTermWidget::setLocked(bool enabled) -{ +void QTermWidget::setLocked(bool enabled) { this->setEnabled(!enabled); m_terminalDisplay->setLocked(enabled); } -void QTermWidget::setDrawLineChars(bool drawLineChars) -{ +void QTermWidget::setDrawLineChars(bool drawLineChars) { m_terminalDisplay->setDrawLineChars(drawLineChars); } -void QTermWidget::setBoldIntense(bool boldIntense) -{ +void QTermWidget::setBoldIntense(bool boldIntense) { m_terminalDisplay->setBoldIntense(boldIntense); } @@ -843,8 +748,7 @@ void QTermWidget::setKeyboardCursorColor(bool useForegroundColor, const QColor& m_terminalDisplay->setKeyboardCursorColor(useForegroundColor, color); } -void QTermWidget::addHighLightText(const QString &text, const QColor &color) -{ +void QTermWidget::addHighLightText(const QString &text, const QColor &color) { for (int i = 0; i < m_highLightTexts.size(); i++) { if (m_highLightTexts.at(i)->text == text) { return; @@ -857,8 +761,7 @@ void QTermWidget::addHighLightText(const QString &text, const QColor &color) m_terminalDisplay->repaint(); } -QMap QTermWidget::getHighLightTexts(void) -{ +QMap QTermWidget::getHighLightTexts(void) { QMap highLightTexts; for (int i = 0; i < m_highLightTexts.size(); i++) { highLightTexts.insert(m_highLightTexts.at(i)->text, m_highLightTexts.at(i)->color); @@ -866,8 +769,7 @@ QMap QTermWidget::getHighLightTexts(void) return highLightTexts; } -bool QTermWidget::isContainHighLightText(const QString &text) -{ +bool QTermWidget::isContainHighLightText(const QString &text) { for (int i = 0; i < m_highLightTexts.size(); i++) { if (m_highLightTexts.at(i)->text == text) { return true; @@ -876,8 +778,7 @@ bool QTermWidget::isContainHighLightText(const QString &text) return false; } -void QTermWidget::removeHighLightText(const QString &text) -{ +void QTermWidget::removeHighLightText(const QString &text) { for (int i = 0; i < m_highLightTexts.size(); i++) { if (m_highLightTexts.at(i)->text == text) { m_terminalDisplay->filterChain()->removeFilter(m_highLightTexts.at(i)->regExpFilter); @@ -890,8 +791,7 @@ void QTermWidget::removeHighLightText(const QString &text) m_terminalDisplay->repaint(); } -void QTermWidget::clearHighLightTexts(void) -{ +void QTermWidget::clearHighLightTexts(void) { for (int i = 0; i < m_highLightTexts.size(); i++) { m_terminalDisplay->filterChain()->removeFilter(m_highLightTexts.at(i)->regExpFilter); delete m_highLightTexts.at(i); @@ -901,8 +801,7 @@ void QTermWidget::clearHighLightTexts(void) m_terminalDisplay->repaint(); } -void QTermWidget::setWordCharacters(const QString &wordCharacters) -{ +void QTermWidget::setWordCharacters(const QString &wordCharacters) { m_terminalDisplay->setWordCharacters(wordCharacters); } diff --git a/lib/qtermwidget/qtermwidget.h b/lib/qtermwidget/qtermwidget.h index a3d0e015..281d2fe5 100644 --- a/lib/qtermwidget/qtermwidget.h +++ b/lib/qtermwidget/qtermwidget.h @@ -1,22 +1,21 @@ -/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 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 - Library 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. +/* + Copyright (C) 2008 e_k (e_k@users.sourceforge.net) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 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 + Library 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 _Q_TERM_WIDGET #define _Q_TERM_WIDGET diff --git a/lib/qtermwidget/qtermwidget.pri b/lib/qtermwidget/qtermwidget.pri index 1e278ab7..0fea7573 100644 --- a/lib/qtermwidget/qtermwidget.pri +++ b/lib/qtermwidget/qtermwidget.pri @@ -29,15 +29,12 @@ HEADERS += \ $$PWD/Character.h \ $$PWD/ColorScheme.h \ $$PWD/ColorTables.h \ - $$PWD/DefaultTranslatorText.h \ $$PWD/Emulation.h \ - $$PWD/ExtendedDefaultTranslator.h \ $$PWD/Filter.h \ $$PWD/History.h \ $$PWD/HistorySearch.h \ $$PWD/KeyboardTranslator.h \ $$PWD/CharWidth.h \ - $$PWD/LineFont.h \ $$PWD/qtermwidget.h \ $$PWD/qtermwidget_version.h \ $$PWD/Screen.h \ diff --git a/lib/qtermwidget/qtermwidget_version.h b/lib/qtermwidget/qtermwidget_version.h index 729e4376..7b5d938c 100644 --- a/lib/qtermwidget/qtermwidget_version.h +++ b/lib/qtermwidget/qtermwidget_version.h @@ -1,19 +1,20 @@ -/* Copyright (C) 2020 Axel Kittenberger (axel.kittenberger@univie.ac.at) +/* + Copyright (C) 2020 Axel Kittenberger (axel.kittenberger@univie.ac.at) - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 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 - Library 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. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 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 + Library 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 _Q_TERM_WIDGET_VERSION #define _Q_TERM_WIDGET_VERSION diff --git a/lib/qtermwidget/tools.cpp b/lib/qtermwidget/tools.cpp index 800e2622..56d8b32b 100644 --- a/lib/qtermwidget/tools.cpp +++ b/lib/qtermwidget/tools.cpp @@ -4,44 +4,37 @@ #include #include - Q_LOGGING_CATEGORY(qtermwidgetLogger, "qtermwidget", QtWarningMsg) /*! Helper function to get possible location of layout files. -By default the KB_LAYOUT_DIR is used (linux/BSD/macports). -But in some cases (apple bundle) there can be more locations). -*/ -QString get_kb_layout_dir() -{ + By default the KB_LAYOUT_DIR is used (linux/BSD/macports). + But in some cases (apple bundle) there can be more locations). + */ +QString get_kb_layout_dir() { QString rval = QString(); QString k(QLatin1String(":/lib/qtermwidget/kb-layouts")); QDir d(k); - if (d.exists()) - { + if (d.exists()) { rval = k.append(QLatin1Char('/')); return rval; } - + return QString(); } /*! Helper function to add custom location of color schemes. -*/ -namespace { - QStringList custom_color_schemes_dirs; -} -void add_custom_color_scheme_dir(const QString& custom_dir) -{ + */ +static QStringList custom_color_schemes_dirs; +void add_custom_color_scheme_dir(const QString &custom_dir) { if (!custom_color_schemes_dirs.contains(custom_dir)) custom_color_schemes_dirs << custom_dir; } /*! Helper function to get possible locations of color schemes. -By default the COLORSCHEMES_DIR is used (linux/BSD/macports). -But in some cases (apple bundle) there can be more locations). + By default the COLORSCHEMES_DIR is used (linux/BSD/macports). + But in some cases (apple bundle) there can be more locations). */ -const QStringList get_color_schemes_dirs() -{ +const QStringList get_color_schemes_dirs() { QStringList rval; QString k(QLatin1String(":/lib/qtermwidget/color-schemes")); QDir d(k); @@ -49,15 +42,13 @@ const QStringList get_color_schemes_dirs() if (d.exists()) rval << k.append(QLatin1Char('/')); - - for (const QString& custom_dir : std::as_const(custom_color_schemes_dirs)) - { + for (const QString &custom_dir : std::as_const(custom_color_schemes_dirs)) { d.setPath(custom_dir); if (d.exists()) rval << custom_dir; } #ifdef QT_DEBUG - if(rval.isEmpty()) { + if (rval.isEmpty()) { qDebug() << "Cannot find color-schemes in any location!"; } #endif