-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2606 lines (2258 loc) · 107 KB
/
main.js
File metadata and controls
2606 lines (2258 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { app, BrowserWindow, ipcMain, globalShortcut, clipboard, Menu, Tray, nativeImage, screen, dialog } from 'electron';
import { fileURLToPath } from 'url';
import path, { dirname, join } from 'path';
import nativeTheme from 'electron';
import { exec, execSync } from 'child_process';
import { readFile, writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';
import { SimpleLLMEngine } from './simple-llm-engine.js';
import { initI18n, t, changeLanguage, getCurrentLanguage, getPackageVersion, getI18nData } from './i18n.js';
import { defaultSettings } from './default-settings.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Auto-updater (production環境でのみ実行)
if (app.isPackaged) {
try {
// run this as early in the main process as possible
const { default: electronSquirrelStartup } = await import('electron-squirrel-startup');
if (electronSquirrelStartup) {
app.quit();
}
const { updateElectronApp } = await import('update-electron-app');
updateElectronApp();
} catch (error) {
console.log('Auto-updater packages not found. This is normal in development.', error.message);
}
}
/**
* gengo Electron メインプロセス(完全版・ポップアップUI付き)
* ユーザー選択テキストに対してポップアップで処理選択を提供
*/
class GengoElectronMain {
constructor() {
this.popupWindow = null;
this.settingsWindow = null;
this.tray = null;
this.llmEngine = null;
this.currentSelectedText = '';
this.currentProcessingData = null;
this.isApplying = false;
this.isShowingResult = false;
this.appVersion = null;
// デフォルト設定をインポートして使用
this.settings = { ...defaultSettings };
this.settingsPath = join(app.getPath('userData'), 'settings.json');
}
async init() {
nativeTheme.themeSource = 'system';
console.log('gengo Electron: ポップアップUI版で起動中...');
// 設定を読み込み
await this.loadSettings();
// i18n初期化
await initI18n(this.settings.language);
// バージョン情報を取得
this.appVersion = await getPackageVersion();
// LLM設定を出力
console.log('LLM設定詳細:', this.getLLMConfig());
// LLMエンジン初期化
this.llmEngine = this.createLLMEngine();
// システムトレイを作成
this.createTray();
// グローバルショートカットを登録
this.registerGlobalShortcuts();
// IPC イベントハンドラーを設定
this.setupIPCHandlers();
console.log('gengo Electron: 初期化完了');
}
/**
* プラットフォーム判定ヘルパー
*/
isMac() {
return process.platform === 'darwin';
}
isWindows() {
return process.platform === 'win32';
}
isLinux() {
return process.platform === 'linux';
}
/**
* プラットフォームに応じたコマンドキー名を取得
*/
getCmdKey() {
return this.isMac() ? 'cmd' : 'ctrl';
}
/**
* プラットフォームに応じたコマンドキー表示名を取得
*/
getCmdKeyDisplay() {
return this.isMac() ? '⌘' : 'Ctrl';
}
/**
* システムトレイを作成または更新
*/
createTray() {
try {
// 既存のトレイがある場合は破棄
if (this.tray) {
this.tray.destroy();
this.tray = null;
console.log('既存のシステムトレイを破棄しました');
}
// テキストベースの簡単なアイコンを作成
const isDev = !app.isPackaged;
const icon_path_settings = isDev
? path.join(__dirname, 'images', 'settings.png')
: path.join(process.resourcesPath, 'images', 'settings.png');
const icon_path_about = isDev
? path.join(__dirname, 'images', 'about.png')
: path.join(process.resourcesPath, 'images', 'about.png');
this.tray = new Tray(path.join(__dirname, './icons/IconTemplate.png'))
this.tray.setToolTip(t('tray.tooltip'));
const img_about = nativeImage
.createFromPath(icon_path_about)
.resize({ width: 16, height: 16 }) // 論理サイズ 16px として扱わせる
img_about.setTemplateImage(true)
const img_settings = nativeImage
.createFromPath(icon_path_settings)
.resize({ width: 16, height: 16 }) // 論理サイズ 16px として扱わせる
img_settings.setTemplateImage(true)
const contextMenu = Menu.buildFromTemplate([
{
label: `GenGo v${this.appVersion || 'loading...'}`,
enabled: false
},
{ type: 'separator' },
{
icon: img_about,
label: t('tray.about'),
click: () => this.showAbout()
},
{
icon: img_settings,
label: t('tray.settings'),
click: () => this.showSettings()
},
{
role: 'quit',
}
]);
this.tray.setContextMenu(contextMenu);
console.log('システムトレイを作成しました');
} catch (error) {
console.error('システムトレイ作成エラー:', error);
}
}
/**
* LLM設定を取得
*/
getLLMConfig() {
if (this.settings.llmProvider === 'remote') {
return {
provider: 'remote',
apiEndpoint: this.settings.llmEndpoint,
apiKey: this.settings.apiKey,
model: this.settings.modelName || 'gpt-3.5-turbo',
maxTokens: this.settings.maxTokens || 4096
};
} else {
return {
provider: 'local',
apiEndpoint: this.settings.llmEndpoint,
model: this.settings.localModelInstanceId || '',
maxTokens: this.settings.maxTokens || 4096
};
}
}
async rememberLocalReasoningUnsupportedModel(modelId) {
if (!modelId) {
return;
}
const current = Array.isArray(this.settings.localReasoningUnsupportedModels)
? this.settings.localReasoningUnsupportedModels
: [];
if (current.includes(modelId)) {
return;
}
this.settings.localReasoningUnsupportedModels = [...current, modelId];
try {
await writeFile(this.settingsPath, JSON.stringify(this.settings, null, 2));
console.log('reasoning非対応モデルを保存しました:', modelId);
} catch (error) {
console.error('reasoning非対応モデル保存エラー:', error);
}
}
createLLMEngine(config = null) {
const llmConfig = config || this.getLLMConfig();
return new SimpleLLMEngine({
...llmConfig,
localReasoningUnsupportedModels: this.settings.localReasoningUnsupportedModels || [],
onLocalReasoningUnsupportedModel: async (modelId) => {
await this.rememberLocalReasoningUnsupportedModel(modelId);
}
});
}
normalizeLocalEndpoint(endpoint) {
let base = (endpoint || '').trim();
if (!base) {
return 'http://127.0.0.1:1234';
}
if (base.endsWith('/')) {
base = base.slice(0, -1);
}
if (base.endsWith('/api/v1')) {
return base.slice(0, -7);
}
if (base.endsWith('/v1')) {
return base.slice(0, -3);
}
return base;
}
buildLocalApiBase(endpoint) {
return `${this.normalizeLocalEndpoint(endpoint)}/api/v1`;
}
async fetchLocalModels(endpoint) {
const apiBase = this.buildLocalApiBase(endpoint || this.settings.llmEndpoint);
const response = await fetch(`${apiBase}/models`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch local models: ${response.status} ${errorText}`);
}
const payload = await response.json();
const models = Array.isArray(payload?.models)
? payload.models
: (Array.isArray(payload?.data) ? payload.data : []);
const loadedInstances = [];
models.forEach((model) => {
const instances = Array.isArray(model?.loaded_instances) ? model.loaded_instances : [];
instances.forEach((instance) => {
if (instance?.id) {
loadedInstances.push({
id: instance.id,
modelKey: model.key || '',
displayName: model.display_name || model.key || instance.id
});
}
});
});
return {
apiBase,
models,
loadedInstances
};
}
/**
* ショートカットキーの有効性を検証
*/
validateShortcutKey(shortcut) {
try {
// 基本的なショートカットキーの形式をチェック
const validModifiers = ['Cmd', 'Ctrl', 'Alt', 'Shift', 'CmdOrCtrl'];
const parts = shortcut.split('+');
if (parts.length < 2) {
return false;
}
const modifiers = parts.slice(0, -1);
const key = parts[parts.length - 1];
// モディファイアキーの検証
for (const modifier of modifiers) {
if (!validModifiers.includes(modifier)) {
return false;
}
}
// キーの検証(基本的な文字、数字、ファンクションキー)
const validKeyPattern = /^([a-zA-Z0-9]|F[1-9]|F1[0-2]|Space|Tab|Enter|Escape|Delete|Backspace|Up|Down|Left|Right|Home|End|PageUp|PageDown|Insert|;|,|\.|\/|\\|\[|\]|'|`|-|=)$/;
if (!validKeyPattern.test(key)) {
return false;
}
return true;
} catch (error) {
console.error('ショートカットキー検証エラー:', error);
return false;
}
}
/**
* グローバルショートカットを登録
*/
registerGlobalShortcuts() {
try {
// 既存のショートカットをすべて解除
globalShortcut.unregisterAll();
console.log('既存のショートカットをすべて解除しました');
// 事前プロンプトのショートカットを登録
if (this.settings.presetPrompts && Array.isArray(this.settings.presetPrompts)) {
this.settings.presetPrompts.forEach((preset, index) => {
if (preset.enabled && preset.shortcutKey) {
const registered = globalShortcut.register(preset.shortcutKey, () => {
this.handlePresetPromptTrigger(index);
});
if (registered) {
console.log(`事前プロンプト ${index + 1} のショートカット ${preset.shortcutKey} を登録しました`);
} else {
console.error(`事前プロンプト ${index + 1} のショートカット登録に失敗しました: ${preset.shortcutKey}`);
}
}
});
}
// オンデマンドプロンプトモード用のショートカット(設定から取得)
const onDemandShortcut = this.settings.onDemandShortcutKey;
const onDemandRegistered = globalShortcut.register(onDemandShortcut, () => {
this.handleOnDemandPromptTrigger();
});
if (onDemandRegistered) {
console.log(`オンデマンドプロンプトショートカット ${onDemandShortcut} を登録しました`);
} else {
console.error('オンデマンドプロンプトショートカット登録に失敗しました');
}
} catch (error) {
console.error('グローバルショートカット登録エラー:', error);
}
}
/**
* 事前プロンプトトリガー処理(プロンプトインデックス指定)
*/
async handlePresetPromptTrigger(presetIndex) {
try {
// プロンプト設定を取得
const preset = this.settings.presetPrompts[presetIndex];
if (!preset || !preset.enabled) {
console.log(`事前プロンプト ${presetIndex + 1} が無効または存在しません`);
return;
}
console.log(`事前プロンプト ${presetIndex + 1} トリガー実行:`, preset.prompt);
// 結果表示中の場合は Apply を実行
if (this.isShowingResult && this.currentProcessingData) {
console.log('結果表示中のため、Apply処理を実行します');
await this.handleApplyResult();
return;
}
// 既に処理中の場合は無視
if (this.isProcessing) {
console.log(t('processing.messages.processing'));
return;
}
this.isProcessing = true;
console.log('テキスト選択トリガー実行');
// 現在のアプリケーション情報を取得・記憶
await this.captureSelectionContext();
// 現在のクリップボードを保存
const originalClipboard = clipboard.readText();
const clipboardPreview = originalClipboard.length > 50
? originalClipboard.substring(0, 50) + '...'
: originalClipboard;
console.log('元のクリップボード保存:', clipboardPreview);
// アクティブアプリケーションを確認(macOSのみ)
const cmdKey = this.getCmdKey();
if (this.isMac()) {
try {
const activeApp = execSync('osascript -e "tell application \\"System Events\\" to get name of first application process whose frontmost is true"').toString().trim();
console.log('アクティブアプリケーション (macOS):', activeApp);
} catch (error) {
console.error('アクティブアプリケーション取得エラー:', error.message);
}
} else {
console.log('プラットフォーム:', process.platform);
}
// クリップボードを一時的にクリアして選択テキストの検出を確実にする
clipboard.writeText('__GENGO_TEMP_MARKER__');
// Cmd+C (Mac) または Ctrl+C (Windows)でテキストをコピー
console.log(`${this.getCmdKeyDisplay()}+C実行中...`);
await this.simulateKeyPress('c', [cmdKey]);
console.log(`${this.getCmdKeyDisplay()}+C実行完了`);
// 少し待ってからクリップボードを確認(短縮:500ms → 200ms)
setTimeout(() => {
const selectedText = clipboard.readText();
const selectedTextLength = selectedText ? selectedText.length : 0;
console.log('コピー後のクリップボード:', selectedText.substring(0, 100) + '...');
console.log('コピーされたテキストの長さ:', selectedTextLength);
console.log('テンポラリマーカーと同じか:', selectedText === '__GENGO_TEMP_MARKER__');
console.log('テキストが空か:', !selectedText || !selectedText.trim());
// テンポラリマーカーでなく、実際のテキストがコピーされた場合は有効
if (selectedText && selectedText.trim() && selectedText !== '__GENGO_TEMP_MARKER__') {
console.log('選択されたテキスト長:', selectedTextLength, '文字');
console.log('選択コンテキスト:', this.selectionContext);
this.currentSelectedText = selectedText;
// プロンプトを使用してウィンドウ表示(非同期なのでブロックしない)
this.showActionPopupWithPrompt(selectedText, preset.prompt);
// クリップボードを復元
setTimeout(() => {
clipboard.writeText(originalClipboard);
this.isProcessing = false; // フラグをリセット
}, 100);
} else {
console.log('テキスト選択なし - テキスト生成モードに移行');
console.log('- selectedText長:', selectedTextLength);
console.log('- selectedText先頭100文字:', selectedText.substring(0, 100));
console.log('- __GENGO_TEMP_MARKER__と同じか:', selectedText === '__GENGO_TEMP_MARKER__');
console.log('- テキストが空か:', !selectedText || !selectedText.trim());
// テキスト生成モードでポップアップを表示
this.showTextGenerationPopup();
// クリップボードを復元
clipboard.writeText(originalClipboard);
this.isProcessing = false; // フラグをリセット
}
}, 200); // 500ms → 200msに短縮
} catch (error) {
console.error('テキスト選択処理エラー:', error);
this.isProcessing = false; // エラー時もフラグをリセット
}
}
/**
* テキスト選択トリガー処理(旧メソッド名、互換性のため残す)
* デフォルトで最初の事前プロンプトを使用
*/
async handleTextSelectionTrigger() {
return this.handlePresetPromptTrigger(0);
}
/**
* オンデマンドプロンプトトリガー処理(Ctrl+Shift+1)
*/
async handleOnDemandPromptTrigger() {
try {
// 結果表示中の場合は Apply を実行
if (this.isShowingResult && this.currentProcessingData) {
console.log('結果表示中のため、Apply処理を実行します');
await this.handleApplyResult();
return;
}
// 既に処理中の場合は無視
if (this.isProcessing) {
console.log(t('processing.messages.processing'));
return;
}
this.isProcessing = true;
console.log('オンデマンドプロンプトトリガー実行');
// 現在のアプリケーション情報を取得・記憶
await this.captureSelectionContext();
// 現在のクリップボードを保存
const originalClipboard = clipboard.readText();
const clipboardPreview = originalClipboard.length > 50
? originalClipboard.substring(0, 50) + '...'
: originalClipboard;
console.log('元のクリップボード保存:', clipboardPreview);
// アクティブアプリケーションを確認(macOSのみ)
const cmdKey = this.getCmdKey();
if (this.isMac()) {
try {
const activeApp = execSync('osascript -e "tell application \\"System Events\\" to get name of first application process whose frontmost is true"').toString().trim();
console.log('アクティブアプリケーション (macOS):', activeApp);
} catch (error) {
console.error('アクティブアプリケーション取得エラー:', error.message);
}
} else {
console.log('プラットフォーム:', process.platform);
}
// クリップボードを一時的にクリアして選択テキストの検出を確実にする
clipboard.writeText('__GENGO_TEMP_MARKER__');
// Cmd+C (Mac) または Ctrl+C (Windows)でテキストをコピー
console.log(`${this.getCmdKeyDisplay()}+C実行中...`);
await this.simulateKeyPress('c', [cmdKey]);
console.log(`${this.getCmdKeyDisplay()}+C実行完了`);
// 少し待ってからクリップボードを確認(長いテキストの場合は時間がかかる可能性がある)
setTimeout(() => {
const selectedText = clipboard.readText();
const selectedTextLength = selectedText ? selectedText.length : 0;
console.log('コピー後のクリップボード:', selectedText.substring(0, 100) + '...');
console.log('コピーされたテキストの長さ:', selectedTextLength);
console.log('テンポラリマーカーと同じか:', selectedText === '__GENGO_TEMP_MARKER__');
console.log('テキストが空か:', !selectedText || !selectedText.trim());
// テンポラリマーカーでなく、実際のテキストがコピーされた場合は有効
if (selectedText && selectedText.trim() && selectedText !== '__GENGO_TEMP_MARKER__') {
console.log('選択されたテキスト長:', selectedTextLength, '文字');
console.log('選択コンテキスト:', this.selectionContext);
this.currentSelectedText = selectedText;
// オンデマンドプロンプト入力画面を表示
this.showOnDemandPromptInput(selectedText);
// クリップボードを復元
setTimeout(() => {
clipboard.writeText(originalClipboard);
this.isProcessing = false; // フラグをリセット
}, 500);
} else {
console.log('テキスト選択に失敗:');
console.log('- selectedText長:', selectedTextLength);
console.log('- selectedText先頭100文字:', selectedText.substring(0, 100));
console.log('- __GENGO_TEMP_MARKER__と同じか:', selectedText === '__GENGO_TEMP_MARKER__');
console.log('- テキストが空か:', !selectedText || !selectedText.trim());
console.log(t('processing.messages.invalid_selection'));
// クリップボードを復元
clipboard.writeText(originalClipboard);
this.isProcessing = false; // フラグをリセット
}
}, 500);
} catch (error) {
console.error('オンデマンドプロンプト処理エラー:', error);
this.isProcessing = false; // エラー時もフラグをリセット
}
}
/**
* 選択時のコンテキスト情報を記憶(改良版・クロスプラットフォーム対応)
*/
async captureSelectionContext() {
return new Promise((resolve) => {
if (this.isMac()) {
// macOS: AppleScriptを使用
const contextScript = `
tell application "System Events"
set frontApp to first application process whose frontmost is true
set appName to name of frontApp
-- アプリケーションの詳細情報を取得
try
set appBundle to bundle identifier of frontApp
set appDisplayName to displayed name of frontApp
return appName & "|" & appBundle & "|" & appDisplayName
on error
return appName & "|unknown|unknown"
end try
end tell
`;
exec(`osascript -e '${contextScript}'`, (error, stdout, stderr) => {
if (!error && stdout) {
const parts = stdout.trim().split('|');
this.selectionContext = {
appName: parts[0],
bundleId: parts[1],
displayName: parts[2],
processName: parts[0],
timestamp: Date.now()
};
console.log('コンテキスト記憶:', this.selectionContext);
} else {
console.error('コンテキスト取得エラー:', error);
this.selectionContext = this._getFallbackContext();
}
resolve();
});
} else if (this.isWindows()) {
// Windows: PowerShellを使用
const psScript = `Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowInfo {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
}
"@
$hwnd = [WindowInfo]::GetForegroundWindow()
$processId = 0
[WindowInfo]::GetWindowThreadProcessId($hwnd, [ref]$processId) | Out-Null
$process = Get-Process -Id $processId -ErrorAction SilentlyContinue
if ($process) {
Write-Output "$($process.ProcessName)|$($process.Id)|$($process.MainWindowTitle)"
} else {
Write-Output "Unknown|0|Unknown"
}`;
exec(`powershell -Command "${psScript.replace(/"/g, '\\"')}"`, (error, stdout, stderr) => {
if (!error && stdout) {
const parts = stdout.trim().split('|');
this.selectionContext = {
appName: parts[0],
bundleId: parts[1],
displayName: parts[2],
processName: parts[0],
timestamp: Date.now()
};
console.log('コンテキスト記憶:', this.selectionContext);
} else {
console.error('コンテキスト取得エラー:', error);
this.selectionContext = this._getFallbackContext();
}
resolve();
});
} else {
// Linux: フォールバック
this.selectionContext = this._getFallbackContext();
resolve();
}
});
}
/**
* フォールバックコンテキスト
*/
_getFallbackContext() {
return {
appName: 'Unknown',
bundleId: 'unknown',
displayName: 'Unknown',
processName: 'Unknown',
timestamp: Date.now()
};
}
/**
* キープレスをシミュレート(クロスプラットフォーム対応)
*/
async simulateKeyPress(key, modifiers = []) {
return new Promise((resolve, reject) => {
if (this.isMac()) {
// macOS: AppleScript
let keystrokeCommand = '';
if (modifiers.length > 0) {
const modifierMap = {
'cmd': 'command',
'ctrl': 'control',
'shift': 'shift',
'alt': 'option',
'option': 'option'
};
const appleModifiers = modifiers.map(mod => modifierMap[mod] || mod).join(' down, ') + ' down';
keystrokeCommand = `keystroke "${key}" using {${appleModifiers}}`;
} else {
keystrokeCommand = `keystroke "${key}"`;
}
const script = `
tell application "System Events"
${keystrokeCommand}
end tell
`;
exec(`osascript -e '${script}'`, (error, stdout, stderr) => {
if (error) {
console.error('AppleScript実行エラー:', error.message);
reject(error);
} else {
resolve();
}
});
} else if (this.isWindows()) {
// Windows: PowerShellでSendKeysを使用
const modifierMap = {
'cmd': '^', // Ctrl
'ctrl': '^', // Ctrl
'shift': '+', // Shift
'alt': '%' // Alt
};
let keyString = key;
if (modifiers.length > 0) {
const modPrefix = modifiers.map(mod => modifierMap[mod] || '').join('');
keyString = modPrefix + key;
}
const psScript = `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait("${keyString}")`;
exec(`powershell -Command "${psScript}"`, (error, stdout, stderr) => {
if (error) {
console.error('PowerShell実行エラー:', error.message);
reject(error);
} else {
resolve();
}
});
} else {
// Linux: xdotoolを使用(要インストール)
const modifierMap = {
'cmd': 'ctrl',
'ctrl': 'ctrl',
'shift': 'shift',
'alt': 'alt'
};
const mods = modifiers.map(mod => modifierMap[mod] || mod);
const modString = mods.length > 0 ? mods.join('+') + '+' : '';
const command = `xdotool key ${modString}${key}`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error('xdotool実行エラー:', error.message);
reject(error);
} else {
resolve();
}
});
}
});
}
/**
* HTMLベースのポップアップウィンドウを作成
*/
createPopupWindow(forceNormalSize = false) {
// 既存のウィンドウが存在し、まだ破棄されていない場合は破棄
if (this.popupWindow && !this.popupWindow.isDestroyed()) {
console.log('既存のポップアップウィンドウを破棄します');
this.popupWindow.destroy();
this.popupWindow = null;
}
console.log('新しいポップアップウィンドウを作成します');
// 自動適用モードかどうかでウィンドウサイズを決定
// ただし、forceNormalSizeがtrueの場合は常に通常サイズ(オンデマンドプロンプト用)
const isAutoMode = this.settings.autoApplyAndClose && !forceNormalSize;
const windowConfig = isAutoMode
? {
width: 100,
height: 100,
minWidth: 100,
minHeight: 100,
maxWidth: 150,
maxHeight: 150,
resizable: false,
scrollable: false,
}
: {
width: 600,
height: 250,
minWidth: 400,
minHeight: 200,
maxWidth: 1000,
maxHeight: 800,
resizable: true,
};
console.log('ウィンドウサイズ設定:', isAutoMode ? '自動適用モード(100x100)' : '通常モード(600x300)');
this.popupWindow = new BrowserWindow({
...windowConfig,
alwaysOnTop: true,
frame: false, // フレームレス
transparent: false,
movable: true,
acceptFirstMouse: true,
// titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: join(__dirname, 'popup-preload.js')
}
});
// スクロール可能なポップアップにするための CSS を挿入
// ポイント:
// - body をスクロール可能にする (overflow: auto)
// - -webkit-app-region: drag をページ全体に適用するとスクロールや選択が阻害されるため
// ドラッグ領域は .drag-region (例えばヘッダ) のみとする
// - 実際の UI 側ではヘッダ要素に .drag-region クラスを付けることを推奨
this.popupWindow.webContents.on('dom-ready', () => {
this.popupWindow.webContents.insertCSS(`
/* 全体をスクロール可能に */
html, body {
height: 100%;
margin: 0;
padding: 0;
overflow: auto;
-webkit-user-select: text;
-webkit-touch-callout: default;
-webkit-font-smoothing: antialiased;
background-color: transparent;
}
/* ドラッグ可能領域は明示的な要素のみ */
.drag-region,card-title{
-webkit-app-region: drag;
}
/* 入力類やボタン等はドラッグ不可にして選択可能にする */
button, a, input, textarea, select, svg, [data-no-drag] {
-webkit-app-region: no-drag;
-webkit-user-select: text;
}
::-webkit-scrollbar-thumb {
background: rgba(0,0,0,0.2);
border-radius: 6px;
}
`).catch(err => {
console.error('ドラッグ/スクロール用CSS挿入エラー:', err);
});
});
// macOS のウィンドウボタン(トラフィックライト)を非表示にする
if (process.platform === 'darwin' && typeof this.popupWindow.setWindowButtonVisibility === 'function') {
this.popupWindow.setWindowButtonVisibility(false);
}
this.popupWindow.loadFile('popup-ui.html');
// ウィンドウが閉じられた時の処理
this.popupWindow.on('closed', () => {
console.log('ポップアップウィンドウが閉じられました');
this.popupWindow = null;
this.isShowingResult = false; // 結果表示フラグをリセット
this.currentProcessingData = null; // 処理データもリセット
// macOSでDockアイコンを再び非表示にする
if (process.platform === 'darwin') {
app.dock.hide();
}
});
return this.popupWindow;
}
/**
* ポップアップウィンドウを表示
*/
showPopupWindow(mode = 'normal', cursorPosition = null) {
// 既存のウィンドウがあれば閉じる
if (this.popupWindow && !this.popupWindow.isDestroyed()) {
this.popupWindow.destroy();
this.popupWindow = null;
}
// 新しいウィンドウを作成
this.popupWindow = this.createPopupWindow(mode === 'onDemand');
// 自動適用モード時のウィンドウサイズ調整
if (mode === 'autoApply' && this.settings.autoApplyAndClose) {
this.popupWindow.setSize(100, 100);
} else {
this.popupWindow.setSize(600, 300);
}
// カーソル位置を設定
if (cursorPosition) {
this.popupWindow.setPosition(cursorPosition.x, cursorPosition.y);
} else {
// デフォルト位置:画面中央
const bounds = screen.getPrimaryDisplay().bounds;
this.popupWindow.setPosition(
Math.floor(bounds.x + (bounds.width - 600) / 2),
Math.floor(bounds.y + (bounds.height - 300) / 2)
);
}
// Dockに表示
if (process.platform === 'darwin') {
app.dock.show().catch(() => { });
}
// ウィンドウを表示
this.popupWindow.show();
this.popupWindow.focus();
}
/**
* カーソル位置を取得
*/
async getCursorPosition() {
try {
// 全ディスプレイ情報をログ出力
const displays = screen.getAllDisplays();
console.log('利用可能なディスプレイ:');
displays.forEach((display, index) => {
const bounds = display.bounds;
const workArea = display.workArea;
console.log(` ディスプレイ ${index + 1} (${display.id}):
bounds=(${bounds.x}, ${bounds.y}, ${bounds.width}, ${bounds.height}),
workArea=(${workArea.x}, ${workArea.y}, ${workArea.width}, ${workArea.height}),
primary=${display === screen.getPrimaryDisplay()}`);
});
// ElectronのAPIを使ってカーソル位置を取得
const cursorPoint = screen.getCursorScreenPoint();
console.log(`カーソル位置取得成功: マウス(${cursorPoint.x}, ${cursorPoint.y})`);
return { x: cursorPoint.x, y: cursorPoint.y };
} catch (error) {
console.error('カーソル位置取得エラー:', error);
// フォールバック:現在のディスプレイの中央を使用
const display = screen.getPrimaryDisplay();
const { width, height } = display.workAreaSize;
const x = width / 2;
const y = height / 2;
console.log(`フォールバック位置を使用: (${x}, ${y})`);
return { x, y };
}
}
/**
* テキスト生成モード用のポップアップを表示
*/
async showTextGenerationPopup() {
console.log('テキスト生成モードでポップアップを表示');
// macOSでポップアップ表示時にDockアイコンを一時的に表示
if (process.platform === 'darwin') {
// app.dock.show();
}
// カーソル位置を取得
const cursorPos = await this.getCursorPosition();
// カーソル位置に最も近いディスプレイを取得
const display = screen.getDisplayNearestPoint({ x: cursorPos.x, y: cursorPos.y });
const { x: displayX, y: displayY, width: screenWidth, height: screenHeight } = display.workArea;
console.log(`ディスプレイ情報: bounds=(${displayX}, ${displayY}, ${screenWidth}, ${screenHeight})`);
console.log(`カーソル位置: (${cursorPos.x}, ${cursorPos.y})`);
// ウィンドウサイズ
const windowWidth = 400;
const windowHeight = 300;
// ウィンドウ位置を計算(カーソル近くに配置)
let windowX = cursorPos.x + 20;
let windowY = cursorPos.y + 20;
// 画面境界チェック
if (windowX + windowWidth > displayX + screenWidth) {
windowX = cursorPos.x - windowWidth - 20;
}
if (windowY + windowHeight > displayY + screenHeight) {
windowY = cursorPos.y - windowHeight - 20;
}