FlatCAMApp.py 324 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. from stat import S_IREAD, S_IRGRP, S_IROTH
  14. import subprocess
  15. import tkinter as tk
  16. from PyQt5 import QtPrintSupport
  17. import urllib.request, urllib.parse, urllib.error
  18. from contextlib import contextmanager
  19. import gc
  20. from xml.dom.minidom import parseString as parse_xml_string
  21. ########################################
  22. ## Imports part of FlatCAM ##
  23. ########################################
  24. from ObjectCollection import *
  25. from FlatCAMObj import *
  26. from flatcamGUI.PlotCanvas import *
  27. from flatcamGUI.FlatCAMGUI import *
  28. from FlatCAMCommon import LoudDict
  29. from FlatCAMPostProc import load_postprocessors
  30. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  31. from FlatCAMProcess import *
  32. from FlatCAMWorkerStack import WorkerStack
  33. from flatcamGUI.VisPyVisuals import Color
  34. from vispy.gloo.util import _screenshot
  35. from vispy.io import write_png
  36. from flatcamTools import *
  37. from multiprocessing import Pool
  38. import tclCommands
  39. import gettext
  40. import FlatCAMTranslation as fcTranslate
  41. fcTranslate.apply_language('strings')
  42. import builtins
  43. if '_' not in builtins.__dict__:
  44. _ = gettext.gettext
  45. ########################################
  46. ## App ##
  47. ########################################
  48. class App(QtCore.QObject):
  49. """
  50. The main application class. The constructor starts the GUI.
  51. """
  52. # Get Cmd Line Options
  53. cmd_line_shellfile = ''
  54. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  55. try:
  56. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  57. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  58. except getopt.GetoptError:
  59. print(cmd_line_help)
  60. sys.exit(2)
  61. for opt, arg in cmd_line_options:
  62. if opt == '-h':
  63. print(cmd_line_help)
  64. sys.exit()
  65. elif opt == '--shellfile':
  66. cmd_line_shellfile = arg
  67. # Logging ##
  68. log = logging.getLogger('base')
  69. log.setLevel(logging.DEBUG)
  70. # log.setLevel(logging.WARNING)
  71. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  72. handler = logging.StreamHandler()
  73. handler.setFormatter(formatter)
  74. log.addHandler(handler)
  75. # Version
  76. version = 8.912
  77. version_date = "2019/03/11"
  78. beta = True
  79. # current date now
  80. date = str(datetime.today()).rpartition(' ')[0]
  81. # URL for update checks and statistics
  82. version_url = "http://flatcam.org/version"
  83. # App URL
  84. app_url = "http://flatcam.org"
  85. # Manual URL
  86. manual_url = "http://flatcam.org/manual/index.html"
  87. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  88. should_we_quit = True
  89. # this variable will hold the project status
  90. # if True it will mean that the project was modified and not saved
  91. should_we_save = False
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added or deleted from/to the collection
  125. object_status_changed = QtCore.pyqtSignal(object, str)
  126. message = QtCore.pyqtSignal(str, str, str)
  127. # Emmited when shell command is finished(one command only)
  128. shell_command_finished = QtCore.pyqtSignal(object)
  129. # Emitted when multiprocess pool has been recreated
  130. pool_recreated = QtCore.pyqtSignal(object)
  131. # Emitted when an unhandled exception happens
  132. # in the worker task.
  133. thread_exception = QtCore.pyqtSignal(object)
  134. def __init__(self, user_defaults=True, post_gui=None):
  135. """
  136. Starts the application.
  137. :return: app
  138. :rtype: App
  139. """
  140. App.log.info("FlatCAM Starting...")
  141. ###################
  142. ### OS-specific ###
  143. ###################
  144. # Folder for user settings.
  145. if sys.platform == 'win32':
  146. from win32com.shell import shell, shellcon
  147. if platform.architecture()[0] == '32bit':
  148. App.log.debug("Win32!")
  149. else:
  150. App.log.debug("Win64!")
  151. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  152. '\FlatCAM'
  153. self.os = 'windows'
  154. else: # Linux/Unix/MacOS
  155. self.data_path = os.path.expanduser('~') + \
  156. '/.FlatCAM'
  157. self.os = 'unix'
  158. ###############################
  159. ### Setup folders and files ###
  160. ###############################
  161. if not os.path.exists(self.data_path):
  162. os.makedirs(self.data_path)
  163. App.log.debug('Created data folder: ' + self.data_path)
  164. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  165. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  166. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  167. if not os.path.exists(self.postprocessorpaths):
  168. os.makedirs(self.postprocessorpaths)
  169. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  170. # create current_defaults.FlatConfig file if there is none
  171. try:
  172. f = open(self.data_path + '/current_defaults.FlatConfig')
  173. f.close()
  174. except IOError:
  175. App.log.debug('Creating empty current_defaults.FlatConfig')
  176. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  177. json.dump({}, f)
  178. f.close()
  179. # create factory_defaults.FlatConfig file if there is none
  180. try:
  181. f = open(self.data_path + '/factory_defaults.FlatConfig')
  182. f.close()
  183. except IOError:
  184. App.log.debug('Creating empty factory_defaults.FlatConfig')
  185. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  186. json.dump({}, f)
  187. f.close()
  188. try:
  189. f = open(self.data_path + '/recent.json')
  190. f.close()
  191. except IOError:
  192. App.log.debug('Creating empty recent.json')
  193. f = open(self.data_path + '/recent.json', 'w')
  194. json.dump([], f)
  195. f.close()
  196. # Application directory. CHDIR to it. Otherwise, trying to load
  197. # GUI icons will fail as their path is relative.
  198. # This will fail under cx_freeze ...
  199. self.app_home = os.path.dirname(os.path.realpath(__file__))
  200. App.log.debug("Application path is " + self.app_home)
  201. App.log.debug("Started in " + os.getcwd())
  202. # cx_freeze workaround
  203. if os.path.isfile(self.app_home):
  204. self.app_home = os.path.dirname(self.app_home)
  205. os.chdir(self.app_home)
  206. # Create multiprocessing pool
  207. self.pool = Pool()
  208. # variable to store mouse coordinates
  209. self.mouse = [0, 0]
  210. ####################
  211. ## Initialize GUI ##
  212. ####################
  213. # FlatCAM colors used in plotting
  214. self.FC_light_green = '#BBF268BF'
  215. self.FC_dark_green = '#006E20BF'
  216. self.FC_light_blue = '#a5a5ffbf'
  217. self.FC_dark_blue = '#0000ffbf'
  218. QtCore.QObject.__init__(self)
  219. self.ui = FlatCAMGUI(self.version, self.beta, self)
  220. # self.connect(self.ui,
  221. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  222. # self.save_geometry) PyQt4
  223. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  224. self.ui.final_save.connect(self.final_save)
  225. ##############
  226. #### Data ####
  227. ##############
  228. self.recent = []
  229. self.clipboard = QtWidgets.QApplication.clipboard()
  230. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  231. self.project_filename = None
  232. self.toggle_units_ignore = False
  233. # self.defaults_form = PreferencesUI()
  234. # when adding entries here read the comments in the method found bellow named:
  235. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  236. self.defaults_form_fields = {
  237. # General App
  238. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  239. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  240. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  241. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  242. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  243. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  244. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  245. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  246. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  247. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  248. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  249. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  250. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  251. # General GUI Preferences
  252. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  253. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  254. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  255. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  256. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  257. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  258. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  259. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  260. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  261. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  262. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  263. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  264. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  265. # General GUI Settings
  266. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  267. # Gerber General
  268. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  269. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  270. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  271. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  272. # Gerber Options
  273. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  274. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  275. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  276. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  277. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  278. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  279. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  280. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  281. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  282. # Gerber Advanced Options
  283. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  284. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  285. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  286. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  287. # Excellon General
  288. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  289. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  290. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  291. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  292. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  293. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  294. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  295. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  296. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  297. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  298. # Excellon Options
  299. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  300. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  301. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  302. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  303. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  304. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  305. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  306. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  307. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  308. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  309. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  310. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  311. # Excellon Advanced Options
  312. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  313. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  314. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  315. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  316. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  317. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  318. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  319. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  320. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  321. # Excellon Export
  322. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  323. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  324. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  325. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  326. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  327. # Geometry General
  328. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  329. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  330. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  331. # Geometry Options
  332. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  333. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  334. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  335. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  336. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  337. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  338. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  339. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  340. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  341. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  342. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  343. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  344. # Geometry Advanced Options
  345. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  346. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  347. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  348. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  349. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  350. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  351. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  352. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  353. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  354. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  355. # CNCJob General
  356. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  357. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  358. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  359. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  360. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  361. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  362. # CNC Job Options
  363. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  364. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  365. # CNC Job Advanced Options
  366. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  367. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  368. # NCC Tool
  369. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  370. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  371. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  372. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  373. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  374. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  375. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  376. # CutOut Tool
  377. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  378. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  379. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  380. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  381. # Paint Area Tool
  382. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  383. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  384. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  385. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  386. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  387. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  388. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  389. # 2-sided Tool
  390. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  391. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  392. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  393. # Film Tool
  394. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  395. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  396. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  397. # Panelize Tool
  398. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  399. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  400. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  401. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  402. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  403. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  404. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  405. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  406. # Calculators Tool
  407. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  408. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  409. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  410. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  411. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  412. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  413. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  414. # Transformations Tool
  415. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  416. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  417. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  418. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  419. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  420. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  421. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  422. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  423. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  424. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  425. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  426. # SolderPaste Dispensing Tool
  427. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  428. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  429. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  430. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  431. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  432. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  433. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  434. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  435. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  436. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  437. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  438. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  439. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  440. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  441. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  442. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  443. }
  444. #############################
  445. #### LOAD POSTPROCESSORS ####
  446. #############################
  447. self.postprocessors = load_postprocessors(self)
  448. for name in list(self.postprocessors.keys()):
  449. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  450. if name.partition('_')[0] == 'Paste':
  451. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  452. continue
  453. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  454. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  455. if name == 'hpgl':
  456. continue
  457. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  458. #############################
  459. #### LOAD LANGUAGES ####
  460. #############################
  461. self.languages = fcTranslate.load_languages()
  462. for name in sorted(self.languages.values()):
  463. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  464. self.defaults = LoudDict()
  465. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  466. self.defaults.update({
  467. # Global APP Preferences
  468. "global_serial": 0,
  469. "global_stats": {},
  470. "units": "IN",
  471. "global_app_level": 'b',
  472. "global_language": 'English',
  473. "global_version_check": True,
  474. "global_send_stats": True,
  475. "global_pan_button": '2',
  476. "global_mselect_key": 'Control',
  477. "global_project_at_startup": False,
  478. "global_project_autohide": True,
  479. "global_toggle_tooltips": True,
  480. "global_compression_level": 3,
  481. "global_save_compressed": True,
  482. # Global GUI Preferences
  483. "global_gridx": 0.0393701,
  484. "global_gridy": 0.0393701,
  485. "global_snap_max": 0.001968504,
  486. "global_workspace": False,
  487. "global_workspaceT": "A4P",
  488. "global_grid_context_menu": {
  489. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  490. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  491. },
  492. "global_plot_fill": '#BBF268BF',
  493. "global_plot_line": '#006E20BF',
  494. "global_sel_fill": '#a5a5ffbf',
  495. "global_sel_line": '#0000ffbf',
  496. "global_alt_sel_fill": '#BBF268BF',
  497. "global_alt_sel_line": '#006E20BF',
  498. "global_draw_color": '#FF0000',
  499. "global_sel_draw_color": '#0000FF',
  500. "global_toolbar_view": 127,
  501. "global_background_timeout": 300000, # Default value is 5 minutes
  502. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  503. # (python trace only for unknown errors),
  504. # 1 = show trace(show trace allways),
  505. # 2 = (For the future).
  506. # Persistence
  507. "global_last_folder": None,
  508. "global_last_save_folder": None,
  509. # Default window geometry
  510. "global_def_win_x": 100,
  511. "global_def_win_y": 100,
  512. "global_def_win_w": 1024,
  513. "global_def_win_h": 650,
  514. # Constants...
  515. "global_defaults_save_period_ms": 20000, # Time between default saves.
  516. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  517. "global_shell_at_startup": False, # Show the shell at startup.
  518. "global_recent_limit": 10, # Max. items in recent list.
  519. "fit_key": 'V',
  520. "zoom_out_key": '-',
  521. "zoom_in_key": '=',
  522. "grid_toggle_key": 'G',
  523. "zoom_ratio": 1.5,
  524. "global_point_clipboard_format": "(%.4f, %.4f)",
  525. "global_zdownrate": None,
  526. # General GUI Settings
  527. "global_hover": True,
  528. # Gerber General
  529. "gerber_plot": True,
  530. "gerber_solid": True,
  531. "gerber_multicolored": False,
  532. "gerber_isotooldia": 0.016,
  533. "gerber_isopasses": 1,
  534. "gerber_isooverlap": 0.15,
  535. # Gerber Options
  536. "gerber_combine_passes": False,
  537. "gerber_milling_type": "cl",
  538. "gerber_noncoppermargin": 0.1,
  539. "gerber_noncopperrounded": False,
  540. "gerber_bboxmargin": 0.1,
  541. "gerber_bboxrounded": False,
  542. "gerber_circle_steps": 64,
  543. "gerber_use_buffer_for_union": True,
  544. # Gerber Advanced Options
  545. "gerber_aperture_display": False,
  546. "gerber_aperture_scale_factor": 1.0,
  547. "gerber_aperture_buffer_factor": 0.0,
  548. "gerber_follow": False,
  549. # Excellon General
  550. "excellon_plot": True,
  551. "excellon_solid": True,
  552. "excellon_format_upper_in": 2,
  553. "excellon_format_lower_in": 4,
  554. "excellon_format_upper_mm": 3,
  555. "excellon_format_lower_mm": 3,
  556. "excellon_zeros": "L",
  557. "excellon_units": "INCH",
  558. "excellon_optimization_type": 'B',
  559. "excellon_search_time": 3,
  560. # Excellon Options
  561. "excellon_drillz": -0.1,
  562. "excellon_travelz": 0.1,
  563. "excellon_feedrate": 3.0,
  564. "excellon_spindlespeed": None,
  565. "excellon_dwell": False,
  566. "excellon_dwelltime": 1,
  567. "excellon_toolchange": False,
  568. "excellon_toolchangez": 1.0,
  569. "excellon_ppname_e": 'default',
  570. "excellon_tooldia": 0.016,
  571. "excellon_slot_tooldia": 0.016,
  572. "excellon_gcode_type": "drills",
  573. # Excellon Advanced Options
  574. "excellon_offset": 0.0,
  575. "excellon_toolchangexy": "0.0, 0.0",
  576. "excellon_startz": None,
  577. "excellon_endz": 2.0,
  578. "excellon_feedrate_rapid": 3.0,
  579. "excellon_z_pdepth": -0.02,
  580. "excellon_feedrate_probe": 3.0,
  581. "excellon_f_plunge": False,
  582. "excellon_f_retract": False,
  583. # Excellon Export
  584. "excellon_exp_units": 'INCH',
  585. "excellon_exp_format": 'ndec',
  586. "excellon_exp_integer": 2,
  587. "excellon_exp_decimals": 4,
  588. "excellon_exp_zeros": 'LZ',
  589. # Geometry General
  590. "geometry_plot": True,
  591. "geometry_circle_steps": 64,
  592. "geometry_cnctooldia": 0.016,
  593. # Geometry Options
  594. "geometry_cutz": -0.002,
  595. "geometry_multidepth": False,
  596. "geometry_depthperpass": 0.002,
  597. "geometry_travelz": 0.1,
  598. "geometry_toolchange": False,
  599. "geometry_toolchangez": 1.0,
  600. "geometry_feedrate": 3.0,
  601. "geometry_feedrate_z": 3.0,
  602. "geometry_spindlespeed": None,
  603. "geometry_dwell": False,
  604. "geometry_dwelltime": 1,
  605. "geometry_ppname_g": 'default',
  606. # Geometry Advanced Options
  607. "geometry_toolchangexy": "0.0, 0.0",
  608. "geometry_startz": None,
  609. "geometry_endz": 2.0,
  610. "geometry_feedrate_rapid": 3.0,
  611. "geometry_extracut": False,
  612. "geometry_z_pdepth": -0.02,
  613. "geometry_f_plunge": False,
  614. "geometry_feedrate_probe": 3.0,
  615. "geometry_segx": 0.0,
  616. "geometry_segy": 0.0,
  617. # CNC Job General
  618. "cncjob_plot": True,
  619. "cncjob_plot_kind": 'all',
  620. "cncjob_tooldia": 0.0393701,
  621. "cncjob_coords_decimals": 4,
  622. "cncjob_fr_decimals": 2,
  623. "cncjob_steps_per_circle": 64,
  624. # CNC Job Options
  625. "cncjob_prepend": "",
  626. "cncjob_append": "",
  627. # CNC Job Advanced Options
  628. "cncjob_toolchange_macro": "",
  629. "cncjob_toolchange_macro_enable": False,
  630. "tools_ncctools": "0.0393701, 0.019685",
  631. "tools_nccoverlap": 0.015748,
  632. "tools_nccmargin": 0.00393701,
  633. "tools_nccmethod": "seed",
  634. "tools_nccconnect": True,
  635. "tools_ncccontour": True,
  636. "tools_nccrest": False,
  637. "tools_cutouttooldia": 0.00393701,
  638. "tools_cutoutmargin": 0.00393701,
  639. "tools_cutoutgapsize": 0.005905512,
  640. "tools_gaps_ff": "8",
  641. "tools_painttooldia": 0.07,
  642. "tools_paintoverlap": 0.15,
  643. "tools_paintmargin": 0.0,
  644. "tools_paintmethod": "seed",
  645. "tools_selectmethod": "single",
  646. "tools_pathconnect": True,
  647. "tools_paintcontour": True,
  648. "tools_2sided_mirror_axis": "X",
  649. "tools_2sided_axis_loc": "point",
  650. "tools_2sided_drilldia": 0.0393701,
  651. "tools_film_type": 'neg',
  652. "tools_film_boundary": 0.0393701,
  653. "tools_film_scale": 0,
  654. "tools_panelize_spacing_columns": 0,
  655. "tools_panelize_spacing_rows": 0,
  656. "tools_panelize_columns": 1,
  657. "tools_panelize_rows": 1,
  658. "tools_panelize_constrain": False,
  659. "tools_panelize_constrainx": 0.0,
  660. "tools_panelize_constrainy": 0.0,
  661. "tools_panelize_panel_type": 'gerber',
  662. "tools_calc_vshape_tip_dia": 0.007874,
  663. "tools_calc_vshape_tip_angle": 30,
  664. "tools_calc_vshape_cut_z": 0.000787,
  665. "tools_calc_electro_length": 10.0,
  666. "tools_calc_electro_width": 10.0,
  667. "tools_calc_electro_cdensity":13.0,
  668. "tools_calc_electro_growth": 10.0,
  669. "tools_transform_rotate": 90,
  670. "tools_transform_skew_x": 0.0,
  671. "tools_transform_skew_y": 0.0,
  672. "tools_transform_scale_x": 1.0,
  673. "tools_transform_scale_y": 1.0,
  674. "tools_transform_scale_link": True,
  675. "tools_transform_scale_reference": True,
  676. "tools_transform_offset_x": 0.0,
  677. "tools_transform_offset_y": 0.0,
  678. "tools_transform_mirror_reference": False,
  679. "tools_transform_mirror_point": (0, 0),
  680. "tools_solderpaste_tools": "0.0393701, 0.011811",
  681. "tools_solderpaste_new": 0.011811,
  682. "tools_solderpaste_z_start": 0.00019685039,
  683. "tools_solderpaste_z_dispense": 0.00393701,
  684. "tools_solderpaste_z_stop": 0.00019685039,
  685. "tools_solderpaste_z_travel": 0.00393701,
  686. "tools_solderpaste_z_toolchange": 0.0393701,
  687. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  688. "tools_solderpaste_frxy": 3.0,
  689. "tools_solderpaste_frz": 3.0,
  690. "tools_solderpaste_frz_dispense": 0.0393701,
  691. "tools_solderpaste_speedfwd": 20,
  692. "tools_solderpaste_dwellfwd": 1,
  693. "tools_solderpaste_speedrev": 10,
  694. "tools_solderpaste_dwellrev": 1,
  695. "tools_solderpaste_pp": 'Paste_1'
  696. })
  697. ###############################
  698. ### Load defaults from file ###
  699. ###############################
  700. if user_defaults:
  701. self.load_defaults(filename='current_defaults')
  702. ############################
  703. ##### APPLY APP LANGUAGE ###
  704. ############################
  705. ret_val = fcTranslate.apply_language('strings')
  706. if ret_val == "no language":
  707. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  708. log.debug("Could not find the Language files. The App strings are missing.")
  709. else:
  710. # make the current language the current selection on the language combobox
  711. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  712. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  713. ###################################
  714. ### CREATE UNIQUE SERIAL NUMBER ###
  715. ###################################
  716. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  717. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  718. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  719. self.save_defaults(silent=True)
  720. self.propagate_defaults(silent=True)
  721. self.restore_main_win_geom()
  722. def auto_save_defaults():
  723. try:
  724. self.save_defaults(silent=True)
  725. self.propagate_defaults(silent=True)
  726. finally:
  727. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  728. # the following lines activates automatic defaults save
  729. # if user_defaults:
  730. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  731. # self.options_form = PreferencesUI()
  732. self.options_form_fields = {
  733. "units": self.ui.general_options_form.general_app_group.units_radio,
  734. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  735. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  736. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  737. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  738. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  739. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  740. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  741. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  742. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  743. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  744. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  745. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  746. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  747. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  748. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  749. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  750. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  751. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  752. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  753. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  754. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  755. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  756. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  757. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  758. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  759. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  760. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  761. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  762. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  763. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  764. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  765. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  766. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  767. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  768. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  769. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  770. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  771. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  772. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  773. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  774. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  775. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  776. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  777. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  778. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  779. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  780. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  781. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  782. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  783. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  784. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  785. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  786. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  787. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  788. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  789. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  790. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  791. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  792. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  793. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  794. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  795. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  796. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  797. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  798. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  799. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  800. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  801. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  802. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  803. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  804. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  805. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  806. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  807. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  808. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  809. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  810. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  811. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  812. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  813. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  814. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  815. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  816. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  817. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  818. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  819. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  820. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  821. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  822. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  823. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  824. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  825. }
  826. for name in list(self.postprocessors.keys()):
  827. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  828. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  829. self.options = LoudDict()
  830. self.options.set_change_callback(self.on_options_dict_change)
  831. self.options.update({
  832. "units": "IN",
  833. "global_gridx": 1.0,
  834. "global_gridy": 1.0,
  835. "global_snap_max": 0.05,
  836. "global_background_timeout": 300000, # Default value is 5 minutes
  837. "global_verbose_error_level": 0, # Shell verbosity:
  838. # 0 = default(python trace only for unknown errors),
  839. # 1 = show trace(show trace allways), 2 = (For the future).
  840. "gerber_plot": True,
  841. "gerber_solid": True,
  842. "gerber_multicolored": False,
  843. "gerber_isotooldia": 0.016,
  844. "gerber_isopasses": 1,
  845. "gerber_isooverlap": 0.15,
  846. "gerber_combine_passes": True,
  847. "gerber_noncoppermargin": 0.0,
  848. "gerber_noncopperrounded": False,
  849. "gerber_bboxmargin": 0.0,
  850. "gerber_bboxrounded": False,
  851. "excellon_plot": True,
  852. "excellon_solid": False,
  853. "excellon_format_upper_in": 2,
  854. "excellon_format_lower_in": 4,
  855. "excellon_format_upper_mm": 3,
  856. "excellon_format_lower_mm": 3,
  857. "excellon_units": 'INCH',
  858. "excellon_optimization_type": 'B',
  859. "excellon_search_time": 3,
  860. "excellon_zeros": "L",
  861. "excellon_drillz": -0.1,
  862. "excellon_travelz": 0.1,
  863. "excellon_feedrate": 3.0,
  864. "excellon_feedrate_rapid": 3.0,
  865. "excellon_spindlespeed": None,
  866. "excellon_dwell": True,
  867. "excellon_dwelltime": 1000,
  868. "excellon_toolchange": False,
  869. "excellon_toolchangez": 1.0,
  870. "excellon_toolchangexy": "0.0, 0.0",
  871. "excellon_tooldia": 0.016,
  872. "excellon_ppname_e": 'default',
  873. "excellon_f_plunge": False,
  874. "excellon_startz": None,
  875. "excellon_endz": 2.0,
  876. "geometry_plot": True,
  877. "geometry_segx": 0.0,
  878. "geometry_segy": 0.0,
  879. "geometry_cutz": -0.002,
  880. "geometry_travelz": 0.1,
  881. "geometry_feedrate": 3.0,
  882. "geometry_feedrate_z": 3.0,
  883. "geometry_feedrate_rapid": 3.0,
  884. "geometry_spindlespeed": None,
  885. "geometry_dwell": True,
  886. "geometry_dwelltime": 1000,
  887. "geometry_cnctooldia": 0.016,
  888. "geometry_toolchange": False,
  889. "geometry_toolchangez": 2.0,
  890. "geometry_toolchangexy": "0.0, 0.0",
  891. "geometry_startz": None,
  892. "geometry_endz": 2.0,
  893. "geometry_ppname_g": "default",
  894. "geometry_f_plunge": False,
  895. "geometry_depthperpass": 0.002,
  896. "geometry_multidepth": False,
  897. "geometry_extracut": False,
  898. "cncjob_plot": True,
  899. "cncjob_tooldia": 0.016,
  900. "cncjob_prepend": "",
  901. "cncjob_append": "",
  902. "tools_ncctools": "1.0, 0.5",
  903. "tools_nccoverlap": 0.4,
  904. "tools_nccmargin": 1,
  905. "tools_cutouttooldia": 0.07,
  906. "tools_cutoutmargin": 0.1,
  907. "tools_cutoutgapsize": 0.15,
  908. "tools_gaps_ff": "8",
  909. "tools_painttooldia": 0.07,
  910. "tools_paintoverlap": 0.15,
  911. "tools_paintmargin": 0.0,
  912. "tools_paintmethod": "seed",
  913. "tools_selectmethod": "single",
  914. "tools_pathconnect": True,
  915. "tools_paintcontour": True,
  916. "tools_2sided_mirror_axis": "X",
  917. "tools_2sided_axis_loc": 'point',
  918. "tools_2sided_drilldia": 1,
  919. "tools_film_type": 'neg',
  920. "tools_film_boundary": 1,
  921. "tools_film_scale": 0,
  922. "tools_panelize_spacing_columns": 0,
  923. "tools_panelize_spacing_rows": 0,
  924. "tools_panelize_columns": 1,
  925. "tools_panelize_rows": 1,
  926. "tools_panelize_constrain": False,
  927. "tools_panelize_constrainx": 0.0,
  928. "tools_panelize_constrainy": 0.0
  929. })
  930. self.options.update(self.defaults) # Copy app defaults to project options
  931. self.gen_form = None
  932. self.ger_form = None
  933. self.exc_form = None
  934. self.geo_form = None
  935. self.cnc_form = None
  936. self.tools_form = None
  937. self.on_options_combo_change(0) # Will show the initial form
  938. ### Define OBJECT COLLECTION ###
  939. self.collection = ObjectCollection(self)
  940. self.ui.project_tab_layout.addWidget(self.collection.view)
  941. ###
  942. self.log.debug("Finished creating Object Collection.")
  943. ### Initialize the color box's color in Preferences -> Global -> Color
  944. # Init Plot Colors
  945. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  946. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  947. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  948. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  949. int(self.defaults['global_plot_fill'][7:9], 16))
  950. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  951. int(self.defaults['global_plot_fill'][7:9], 16))
  952. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  953. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  954. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  955. # Init Left-Right Selection colors
  956. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  957. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  958. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  959. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  960. int(self.defaults['global_sel_fill'][7:9], 16))
  961. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  962. int(self.defaults['global_sel_fill'][7:9], 16))
  963. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  964. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  965. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  966. # Init Right-Left Selection colors
  967. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  968. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  969. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  970. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  971. int(self.defaults['global_sel_fill'][7:9], 16))
  972. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  973. int(self.defaults['global_sel_fill'][7:9], 16))
  974. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  975. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  976. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  977. # Init Draw color and Selection Draw Color
  978. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  979. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  980. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  981. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  982. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  983. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  984. #### End of Data ####
  985. #### Plot Area ####
  986. start_plot_time = time.time() # debug
  987. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  988. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  989. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  990. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  991. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  992. # Keys over plot enabled
  993. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  994. self.ui.splitter.setStretchFactor(1, 2)
  995. # So it can receive key presses
  996. self.plotcanvas.vispy_canvas.native.setFocus()
  997. self.app_cursor = self.plotcanvas.new_cursor()
  998. self.app_cursor.enabled = False
  999. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1000. # depending on from where those tools are called different actions can be done
  1001. self.call_source = 'app'
  1002. end_plot_time = time.time()
  1003. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1004. ### EDITOR section
  1005. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1006. self.exc_editor = FlatCAMExcEditor(self)
  1007. #### Adjust tabs width ####
  1008. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1009. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1010. self.collection.view.setMinimumWidth(290)
  1011. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  1012. #### Worker ####
  1013. self.workers = WorkerStack()
  1014. self.worker_task.connect(self.workers.add_task)
  1015. ### Signal handling ###
  1016. ## Custom signals
  1017. self.inform.connect(self.info)
  1018. self.message.connect(self.message_dialog)
  1019. self.progress.connect(self.set_progress_bar)
  1020. self.object_created.connect(self.on_object_created)
  1021. self.object_changed.connect(self.on_object_changed)
  1022. self.object_plotted.connect(self.on_object_plotted)
  1023. self.plots_updated.connect(self.on_plots_updated)
  1024. self.file_opened.connect(self.register_recent)
  1025. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1026. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1027. ## Standard signals
  1028. # Menu
  1029. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1030. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1031. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1032. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1033. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1034. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1035. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1036. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1037. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1038. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1039. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1040. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1041. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1042. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1043. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1044. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1045. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1046. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1047. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1048. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1049. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1050. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  1051. self.ui.menueditedit.triggered.connect(self.object2editor)
  1052. self.ui.menueditok.triggered.connect(self.editor2object)
  1053. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1054. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1055. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1056. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1057. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1058. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1059. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1060. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1061. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1062. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1063. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1064. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1065. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1066. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1067. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1068. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1069. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1070. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1071. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1072. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1073. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1074. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1075. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1076. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1077. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1078. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1079. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1080. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1081. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1082. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1083. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1084. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1085. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1086. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1087. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1088. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1089. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1090. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1091. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1092. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1093. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1094. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1095. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1096. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1097. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1098. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1099. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1100. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1101. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1102. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1103. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1104. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1105. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1106. # ToolBar signals
  1107. self.connect_toolbar_signals()
  1108. # Context Menu
  1109. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1110. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1111. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1112. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1113. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1114. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1115. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1116. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1117. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1118. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1119. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1120. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1121. self.ui.clearplot.triggered.connect(self.clear_plots)
  1122. self.ui.replot.triggered.connect(self.plot_all)
  1123. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1124. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1125. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1126. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1127. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1128. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1129. # Preferences Plot Area TAB
  1130. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1131. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1132. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1133. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1134. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1135. ###############################
  1136. ### GUI PREFERENCES SIGNALS ###
  1137. ###############################
  1138. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1139. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1140. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1141. )
  1142. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(self.on_toggle_units)
  1143. ###############################
  1144. ### GUI PREFERENCES SIGNALS ###
  1145. ###############################
  1146. # Setting plot colors signals
  1147. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1148. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1149. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1150. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1151. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1152. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1153. # Setting selection (left - right) colors signals
  1154. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1155. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1156. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1157. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1158. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1159. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1160. # Setting selection (right - left) colors signals
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1162. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1164. self.on_alt_sf_color_spinner)
  1165. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1166. self.on_alt_sf_color_slider)
  1167. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1168. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1169. # Setting Editor Draw colors signals
  1170. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1171. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1172. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1173. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1174. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1175. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1176. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1177. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1178. self.on_cnc_custom_parameters)
  1179. # Modify G-CODE Plot Area TAB
  1180. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1181. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1182. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1183. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1184. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1185. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1186. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1187. # Object list
  1188. self.collection.view.activated.connect(self.on_row_activated)
  1189. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1190. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1191. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1192. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1193. self.on_excellon_defaults_button)
  1194. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1195. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1196. self.on_excellon_options_button)
  1197. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1198. self.tool_tab_locked = False
  1199. # decide if to show or hide the Notebook side of the screen at startup
  1200. if self.defaults["global_project_at_startup"] is True:
  1201. self.ui.splitter.setSizes([1, 1])
  1202. else:
  1203. self.ui.splitter.setSizes([0, 1])
  1204. ####################
  1205. ### Other setups ###
  1206. ####################
  1207. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1208. self.setup_obj_classes()
  1209. self.setup_recent_items()
  1210. self.setup_component_editor()
  1211. #############
  1212. ### Shell ###
  1213. #############
  1214. ###
  1215. # Auto-complete KEYWORDS
  1216. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1217. 'aligndrill', 'clear',
  1218. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1219. 'export_gcode',
  1220. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1221. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1222. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1223. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1224. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1225. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1226. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1227. ]
  1228. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1229. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1230. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1231. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1232. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1233. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1234. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1235. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1236. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1237. ]
  1238. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1239. self.shell = FCShell(self, version=self.version)
  1240. self.shell._edit.set_model_data(self.myKeywords)
  1241. self.shell.setWindowIcon(self.ui.app_icon)
  1242. self.shell.setWindowTitle("FlatCAM Shell")
  1243. self.shell.resize(*self.defaults["global_shell_shape"])
  1244. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1245. self.shell.append_output("(Type help to get started)\n\n")
  1246. self.init_tcl()
  1247. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1248. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1249. self.ui.shell_dock.setWidget(self.shell)
  1250. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1251. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1252. QtWidgets.QDockWidget.DockWidgetFloatable |
  1253. QtWidgets.QDockWidget.DockWidgetClosable)
  1254. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1255. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1256. if self.defaults["global_shell_at_startup"]:
  1257. self.ui.shell_dock.show()
  1258. else:
  1259. self.ui.shell_dock.hide()
  1260. #########################
  1261. ### Tools and Plugins ###
  1262. #########################
  1263. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1264. self.install_tools()
  1265. ### System Font Parsing ###
  1266. # self.f_parse = ParseFont(self)
  1267. # self.parse_system_fonts()
  1268. # test if the program was started with a script as parameter
  1269. if self.cmd_line_shellfile:
  1270. try:
  1271. with open(self.cmd_line_shellfile, "r") as myfile:
  1272. cmd_line_shellfile_text = myfile.read()
  1273. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1274. except Exception as ext:
  1275. print("ERROR: ", ext)
  1276. sys.exit(2)
  1277. ###########################
  1278. #### Check for updates ####
  1279. ###########################
  1280. # Separate thread (Not worker)
  1281. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1282. if (self.beta is False or self.beta is None) and \
  1283. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1284. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1285. self.thr2 = QtCore.QThread()
  1286. self.worker_task.emit({'fcn': self.version_check,
  1287. 'params': []})
  1288. self.thr2.start()
  1289. ####################################
  1290. #### Variables for global usage ####
  1291. ####################################
  1292. # coordinates for relative position display
  1293. self.rel_point1 = (0, 0)
  1294. self.rel_point2 = (0, 0)
  1295. # variable to store coordinates
  1296. self.pos = (0, 0)
  1297. self.pos_jump = (0, 0)
  1298. # decide if we have a double click or single click
  1299. self.doubleclick = False
  1300. # variable to store if there was motion before right mouse button click (panning)
  1301. self.panning_action = False
  1302. # variable to store if a command is active (then the var is not None) and which one it is
  1303. self.command_active = None
  1304. # variable to store the status of moving selection action
  1305. # None value means that it's not an selection action
  1306. # True value = a selection from left to right
  1307. # False value = a selection from right to left
  1308. self.selection_type = None
  1309. # List to store the objects that are currently loaded in FlatCAM
  1310. # This list is updated on each object creation or object delete
  1311. self.all_objects_list = []
  1312. # List to store the objects that are selected
  1313. self.sel_objects_list = []
  1314. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1315. self.key_modifiers = None
  1316. # Variable to hold the status of the axis
  1317. self.toggle_axis = True
  1318. # Variable to store the status of the fullscreen event
  1319. self.toggle_fscreen = False
  1320. # Variable to store the status of the code editor
  1321. self.toggle_codeeditor = False
  1322. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1323. self.click_noproject = False
  1324. self.cursor = None
  1325. # Variable to store the GCODE that was edited
  1326. self.gcode_edited = ""
  1327. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1328. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1329. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1330. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1331. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1332. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1333. 'mpf']
  1334. self.svg_list = ['svg']
  1335. self.dxf_list = ['dxf']
  1336. self.prj_list = ['flatprj']
  1337. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1338. # flag for polygons not cleared
  1339. self.poly_not_cleared = False
  1340. # VisPy visuals
  1341. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1342. self.isHovering = False
  1343. self.notHovering = True
  1344. ### Save defaults to factory_defaults.FlatConfig file ###
  1345. ### It's done only once after install #############
  1346. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1347. fac_def_from_file = factory_file.read()
  1348. factory_defaults = json.loads(fac_def_from_file)
  1349. # if the file contain an empty dictionary then save the factory defaults into the file
  1350. if not factory_defaults:
  1351. self.save_factory_defaults(silent=False)
  1352. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1353. initial_lay = 'compact'
  1354. self.on_layout(index=None, lay=initial_lay)
  1355. # Set the combobox in Preferences to the current layout
  1356. idx = self.app.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(
  1357. initial_lay.capitalize()
  1358. )
  1359. self.app.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1360. factory_file.close()
  1361. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1362. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1363. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1364. # Post-GUI initialization: Experimental attempt
  1365. # to perform unit tests on the GUI.
  1366. # if post_gui is not None:
  1367. # post_gui(self)
  1368. App.log.debug("END of constructor. Releasing control.")
  1369. # accept a project file as command line parameter
  1370. # the path/file_name must be enclosed in quotes if it contain spaces
  1371. for argument in App.args:
  1372. if '.FlatPrj' in argument:
  1373. try:
  1374. project_name = str(argument)
  1375. if project_name == "":
  1376. self.inform.emit(_("Open cancelled."))
  1377. else:
  1378. # self.open_project(project_name)
  1379. run_from_arg = True
  1380. self.worker_task.emit({'fcn': self.open_project,
  1381. 'params': [project_name, run_from_arg]})
  1382. except Exception as e:
  1383. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1384. if '.FlatConfig' in argument:
  1385. try:
  1386. file_name = str(argument)
  1387. if file_name == "":
  1388. self.inform.emit(_("Open Config file failed."))
  1389. else:
  1390. # run_from_arg = True
  1391. # self.worker_task.emit({'fcn': self.open_config_file,
  1392. # 'params': [file_name, run_from_arg]})
  1393. self.open_config_file(file_name, run_from_arg=True)
  1394. except Exception as e:
  1395. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1396. def defaults_read_form(self):
  1397. for option in self.defaults_form_fields:
  1398. try:
  1399. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1400. except:
  1401. pass
  1402. def defaults_write_form(self, factor=None):
  1403. for option in self.defaults:
  1404. self.defaults_write_form_field(option, factor=factor)
  1405. # try:
  1406. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1407. # except KeyError:
  1408. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1409. # # TODO: Rethink this?
  1410. # pass
  1411. def defaults_write_form_field(self, field, factor=None):
  1412. try:
  1413. if factor is None:
  1414. self.defaults_form_fields[field].set_value(self.defaults[field])
  1415. else:
  1416. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1417. except KeyError:
  1418. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1419. # TODO: Rethink this?
  1420. pass
  1421. except AttributeError:
  1422. log.debug(field)
  1423. def clear_pool(self):
  1424. self.pool.close()
  1425. self.pool = Pool()
  1426. self.pool_recreated.emit(self.pool)
  1427. gc.collect()
  1428. # the order that the tools are installed is important as they can depend on each other install position
  1429. def install_tools(self):
  1430. self.dblsidedtool = DblSidedTool(self)
  1431. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1432. self.measurement_tool = Measurement(self)
  1433. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1434. self.panelize_tool = Panelize(self)
  1435. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1436. self.film_tool = Film(self)
  1437. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1438. self.paste_tool = SolderPaste(self)
  1439. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1440. self.move_tool = ToolMove(self)
  1441. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1442. before=self.ui.menueditorigin)
  1443. self.cutout_tool = CutOut(self)
  1444. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1445. before=self.measurement_tool.menuAction)
  1446. self.ncclear_tool = NonCopperClear(self)
  1447. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1448. before=self.measurement_tool.menuAction, separator=True)
  1449. self.paint_tool = ToolPaint(self)
  1450. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1451. before=self.measurement_tool.menuAction, separator=True)
  1452. self.calculator_tool = ToolCalculator(self)
  1453. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1454. self.transform_tool = ToolTransform(self)
  1455. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1456. self.properties_tool = Properties(self)
  1457. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1458. self.image_tool = ToolImage(self)
  1459. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1460. separator=True)
  1461. self.log.debug("Tools are installed.")
  1462. def remove_tools(self):
  1463. for act in self.ui.menutool.actions():
  1464. self.ui.menutool.removeAction(act)
  1465. def init_tools(self):
  1466. log.debug("init_tools()")
  1467. # delete the data currently in the Tools Tab and the Tab itself
  1468. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1469. if widget is not None:
  1470. widget.deleteLater()
  1471. self.ui.notebook.removeTab(2)
  1472. # rebuild the Tools Tab
  1473. self.ui.tool_tab = QtWidgets.QWidget()
  1474. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1475. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1476. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1477. self.ui.tool_scroll_area = VerticalScrollArea()
  1478. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1479. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1480. # first remove all of them
  1481. self.remove_tools()
  1482. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1483. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1484. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1485. # third install all of them
  1486. self.install_tools()
  1487. self.log.debug("Tools are initialized.")
  1488. # def parse_system_fonts(self):
  1489. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1490. # 'params': []})
  1491. def connect_toolbar_signals(self):
  1492. # Toolbar
  1493. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1494. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1495. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1496. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1497. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1498. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1499. self.ui.replot_btn.triggered.connect(self.plot_all)
  1500. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1501. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1502. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1503. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1504. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1505. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1506. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1507. self.ui.delete_btn.triggered.connect(self.on_delete)
  1508. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1509. # Tools Toolbar Signals
  1510. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1511. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1512. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1513. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1514. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1515. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1516. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1517. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1518. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1519. def object2editor(self):
  1520. """
  1521. Send the current Geometry or Excellon object (if any) into the editor.
  1522. :return: None
  1523. """
  1524. self.report_usage("object2editor()")
  1525. # adjust the visibility of some of the canvas context menu
  1526. self.ui.popmenu_edit.setVisible(False)
  1527. self.ui.popmenu_save.setVisible(True)
  1528. # adjust the status of the menu entries related to the editor
  1529. self.ui.menueditedit.setDisabled(True)
  1530. self.ui.menueditok.setDisabled(False)
  1531. edited_object = self.collection.get_active()
  1532. if isinstance(edited_object, FlatCAMGeometry):
  1533. # for now, if the Geometry is MultiGeo do not allow the editing
  1534. if edited_object.multigeo is True:
  1535. self.inform.emit(_("[WARNING_NOTCL] Editing a MultiGeo Geometry is not possible for the moment."))
  1536. return
  1537. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1538. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1539. self.geo_editor.edit_fcgeometry(edited_object)
  1540. # we set the notebook to hidden
  1541. self.ui.splitter.setSizes([0, 1])
  1542. # set call source to the Editor we go into
  1543. self.call_source = 'geo_editor'
  1544. elif isinstance(edited_object, FlatCAMExcellon):
  1545. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1546. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1547. self.exc_editor.edit_fcexcellon(edited_object)
  1548. # set call source to the Editor we go into
  1549. self.call_source = 'exc_editor'
  1550. else:
  1551. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit."))
  1552. return
  1553. # make sure that we can't select another object while in Editor Mode:
  1554. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1555. # delete any selection shape that might be active as they are not relevant in Editor
  1556. self.delete_selection_shape()
  1557. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1558. self.ui.plot_tab_area.protectTab(0)
  1559. self.inform.emit(_("[WARNING_NOTCL]Editor is activated ..."))
  1560. self.should_we_save = True
  1561. def editor2object(self):
  1562. """
  1563. Transfers the Geometry or Excellon from the editor to the current object.
  1564. :return: None
  1565. """
  1566. self.report_usage("editor2object()")
  1567. # adjust the status of the menu entries related to the editor
  1568. self.ui.menueditedit.setDisabled(False)
  1569. self.ui.menueditok.setDisabled(True)
  1570. # do not update a geometry or excellon object unless it comes out of an editor
  1571. if self.call_source != 'app':
  1572. # adjust the visibility of some of the canvas context menu
  1573. self.ui.popmenu_edit.setVisible(True)
  1574. self.ui.popmenu_save.setVisible(False)
  1575. edited_obj = self.collection.get_active()
  1576. obj_type = ""
  1577. if isinstance(edited_obj, FlatCAMGeometry):
  1578. obj_type = "Geometry"
  1579. self.geo_editor.update_fcgeometry(edited_obj)
  1580. self.geo_editor.update_options(edited_obj)
  1581. self.geo_editor.deactivate()
  1582. # update the geo object options so it is including the bounding box values
  1583. try:
  1584. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1585. edited_obj.options['xmin'] = xmin
  1586. edited_obj.options['ymin'] = ymin
  1587. edited_obj.options['xmax'] = xmax
  1588. edited_obj.options['ymax'] = ymax
  1589. except AttributeError:
  1590. self.inform.emit(_("[WARNING] Object empty after edit."))
  1591. elif isinstance(edited_obj, FlatCAMExcellon):
  1592. obj_type = "Excellon"
  1593. self.exc_editor.update_fcexcellon(edited_obj)
  1594. self.exc_editor.update_options(edited_obj)
  1595. self.exc_editor.deactivate()
  1596. else:
  1597. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to update."))
  1598. return
  1599. # if notebook is hidden we show it
  1600. if self.ui.splitter.sizes()[0] == 0:
  1601. self.ui.splitter.setSizes([1, 1])
  1602. # restore the call_source to app
  1603. self.call_source = 'app'
  1604. edited_obj.plot()
  1605. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1606. self.ui.plot_tab_area.protectTab(0)
  1607. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1608. # reset the Object UI to original settings
  1609. # edited_obj.set_ui(edited_obj.ui_type())
  1610. # edited_obj.build_ui()
  1611. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1612. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1613. def get_last_folder(self):
  1614. return self.defaults["global_last_folder"]
  1615. def get_last_save_folder(self):
  1616. loc = self.defaults["global_last_save_folder"]
  1617. if loc is None:
  1618. loc = self.defaults["global_last_folder"]
  1619. if loc is None:
  1620. loc = os.path.dirname(__file__)
  1621. return loc
  1622. def report_usage(self, resource):
  1623. """
  1624. Increments usage counter for the given resource
  1625. in self.defaults['global_stats'].
  1626. :param resource: Name of the resource.
  1627. :return: None
  1628. """
  1629. if resource in self.defaults['global_stats']:
  1630. self.defaults['global_stats'][resource] += 1
  1631. else:
  1632. self.defaults['global_stats'][resource] = 1
  1633. def init_tcl(self):
  1634. if hasattr(self,'tcl'):
  1635. # self.tcl = None
  1636. # TODO we need to clean non default variables and procedures here
  1637. # new object cannot be used here as it will not remember values created for next passes,
  1638. # because tcl was execudted in old instance of TCL
  1639. pass
  1640. else:
  1641. self.tcl = tk.Tcl()
  1642. self.setup_shell()
  1643. self.log.debug("TCL Shell has been initialized.")
  1644. # TODO: This shouldn't be here.
  1645. class TclErrorException(Exception):
  1646. """
  1647. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1648. """
  1649. pass
  1650. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1651. """
  1652. Shows a message on the FlatCAM Shell
  1653. :param msg: Message to display.
  1654. :param show: Opens the shell.
  1655. :param error: Shows the message as an error.
  1656. :return: None
  1657. """
  1658. if show:
  1659. self.ui.shell_dock.show()
  1660. try:
  1661. if error:
  1662. self.shell.append_error(msg + "\n")
  1663. elif warning:
  1664. self.shell.append_warning(msg + "\n")
  1665. elif success:
  1666. self.shell.append_success(msg + "\n")
  1667. elif selected:
  1668. self.shell.append_selected(msg + "\n")
  1669. else:
  1670. self.shell.append_output(msg + "\n")
  1671. except AttributeError:
  1672. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1673. def raise_tcl_unknown_error(self, unknownException):
  1674. """
  1675. Raise exception if is different type than TclErrorException
  1676. this is here mainly to show unknown errors inside TCL shell console.
  1677. :param unknownException:
  1678. :return:
  1679. """
  1680. if not isinstance(unknownException, self.TclErrorException):
  1681. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1682. else:
  1683. raise unknownException
  1684. def display_tcl_error(self, error, error_info=None):
  1685. """
  1686. escape bracket [ with \ otherwise there is error
  1687. "ERROR: missing close-bracket" instead of real error
  1688. :param error: it may be text or exception
  1689. :return: None
  1690. """
  1691. if isinstance(error, Exception):
  1692. exc_type, exc_value, exc_traceback = error_info
  1693. if not isinstance(error, self.TclErrorException):
  1694. show_trace = 1
  1695. else:
  1696. show_trace = int(self.defaults['global_verbose_error_level'])
  1697. if show_trace > 0:
  1698. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1699. trc_formated = []
  1700. for a in reversed(trc):
  1701. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1702. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1703. exc_type,
  1704. "\n".join(trc_formated))
  1705. else:
  1706. text = "%s" % error
  1707. else:
  1708. text = error
  1709. text = text.replace('[', '\\[').replace('"', '\\"')
  1710. self.tcl.eval('return -code error "%s"' % text)
  1711. def raise_tcl_error(self, text):
  1712. """
  1713. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1714. :param text: text of error
  1715. :return: raise exception
  1716. """
  1717. self.display_tcl_error(text)
  1718. raise self.TclErrorException(text)
  1719. def exec_command(self, text):
  1720. """
  1721. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1722. Also handles execution in separated threads
  1723. :param text:
  1724. :return: output if there was any
  1725. """
  1726. self.report_usage('exec_command')
  1727. result = self.exec_command_test(text, False)
  1728. #MS: added this method call so the geometry is updated once the TCL
  1729. #command is executed
  1730. self.plot_all()
  1731. return result
  1732. def exec_command_test(self, text, reraise=True):
  1733. """
  1734. Same as exec_command(...) with additional control over exceptions.
  1735. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1736. :param text: Input command
  1737. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1738. :return: Output from the command
  1739. """
  1740. text = str(text)
  1741. try:
  1742. self.shell.open_proccessing() # Disables input box.
  1743. result = self.tcl.eval(str(text))
  1744. if result != 'None':
  1745. self.shell.append_output(result + '\n')
  1746. except tk.TclError as e:
  1747. # This will display more precise answer if something in TCL shell fails
  1748. result = self.tcl.eval("set errorInfo")
  1749. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1750. self.shell.append_error('ERROR: ' + result + '\n')
  1751. # Show error in console and just return or in test raise exception
  1752. if reraise:
  1753. raise e
  1754. finally:
  1755. self.shell.close_proccessing()
  1756. pass
  1757. return result
  1758. # """
  1759. # Code below is unsused. Saved for later.
  1760. # """
  1761. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1762. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1763. # self.log.debug(parts)
  1764. # try:
  1765. # if parts[0] not in commands:
  1766. # self.shell.append_error("Unknown command\n")
  1767. # return
  1768. #
  1769. # #import inspect
  1770. # #inspect.getargspec(someMethod)
  1771. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1772. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1773. # self.shell.append_error(
  1774. # "Command %s takes %d arguments. %d given.\n" %
  1775. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1776. # )
  1777. # return
  1778. #
  1779. # cmdfcn = commands[parts[0]]["fcn"]
  1780. # cmdconv = commands[parts[0]]["converters"]
  1781. # if len(parts) - 1 > 0:
  1782. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1783. # else:
  1784. # retval = cmdfcn()
  1785. # retfcn = commands[parts[0]]["retfcn"]
  1786. # if retval and retfcn(retval):
  1787. # self.shell.append_output(retfcn(retval) + "\n")
  1788. #
  1789. # except Exception as e:
  1790. # #self.shell.append_error(''.join(traceback.format_exc()))
  1791. # #self.shell.append_error("?\n")
  1792. # self.shell.append_error(str(e) + "\n")
  1793. def info(self, msg):
  1794. """
  1795. Informs the user. Normally on the status bar, optionally
  1796. also on the shell.
  1797. :param msg: Text to write.
  1798. :return: None
  1799. """
  1800. # Type of message in brackets at the begining of the message.
  1801. match = re.search("\[([^\]]+)\](.*)", msg)
  1802. if match:
  1803. level = match.group(1)
  1804. msg_ = match.group(2)
  1805. self.ui.fcinfo.set_status(str(msg_), level=level)
  1806. if level.lower() == "error":
  1807. self.shell_message(msg, error=True, show=True)
  1808. elif level.lower() == "warning":
  1809. self.shell_message(msg, warning=True, show=True)
  1810. elif level.lower() == "error_notcl":
  1811. self.shell_message(msg, error=True, show=False)
  1812. elif level.lower() == "warning_notcl":
  1813. self.shell_message(msg, warning=True, show=False)
  1814. elif level.lower() == "success":
  1815. self.shell_message(msg, success=True, show=False)
  1816. elif level.lower() == "selected":
  1817. self.shell_message(msg, selected=True, show=False)
  1818. else:
  1819. self.shell_message(msg, show=False)
  1820. else:
  1821. self.ui.fcinfo.set_status(str(msg), level="info")
  1822. # make sure that if the message is to clear the infobar with a space
  1823. # is not printed over and over on the shell
  1824. if msg != '':
  1825. self.shell_message(msg)
  1826. def restore_toolbar_view(self):
  1827. tb = self.defaults["global_toolbar_view"]
  1828. if tb & 1:
  1829. self.ui.toolbarfile.setVisible(True)
  1830. else:
  1831. self.ui.toolbarfile.setVisible(False)
  1832. if tb & 2:
  1833. self.ui.toolbargeo.setVisible(True)
  1834. else:
  1835. self.ui.toolbargeo.setVisible(False)
  1836. if tb & 4:
  1837. self.ui.toolbarview.setVisible(True)
  1838. else:
  1839. self.ui.toolbarview.setVisible(False)
  1840. if tb & 8:
  1841. self.ui.toolbartools.setVisible(True)
  1842. else:
  1843. self.ui.toolbartools.setVisible(False)
  1844. if tb & 16:
  1845. self.ui.exc_edit_toolbar.setVisible(True)
  1846. else:
  1847. self.ui.exc_edit_toolbar.setVisible(False)
  1848. if tb & 32:
  1849. self.ui.geo_edit_toolbar.setVisible(True)
  1850. else:
  1851. self.ui.geo_edit_toolbar.setVisible(False)
  1852. if tb & 64:
  1853. self.ui.snap_toolbar.setVisible(True)
  1854. else:
  1855. self.ui.snap_toolbar.setVisible(False)
  1856. if tb & 128:
  1857. self.ui.toolbarshell.setVisible(True)
  1858. else:
  1859. self.ui.toolbarshell.setVisible(False)
  1860. def load_defaults(self, filename):
  1861. """
  1862. Loads the aplication's default settings from current_defaults.FlatConfig into
  1863. ``self.defaults``.
  1864. :return: None
  1865. """
  1866. try:
  1867. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1868. options = f.read()
  1869. f.close()
  1870. except IOError:
  1871. self.log.error("Could not load defaults file.")
  1872. self.inform.emit(_("[ERROR] Could not load defaults file."))
  1873. # in case the defaults file can't be loaded, show all toolbars
  1874. self.defaults["global_toolbar_view"] = 255
  1875. return
  1876. try:
  1877. defaults = json.loads(options)
  1878. except:
  1879. # in case the defaults file can't be loaded, show all toolbars
  1880. self.defaults["global_toolbar_view"] = 255
  1881. e = sys.exc_info()[0]
  1882. App.log.error(str(e))
  1883. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  1884. return
  1885. self.defaults.update(defaults)
  1886. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1887. # restore the toolbar view
  1888. self.restore_toolbar_view()
  1889. def on_import_preferences(self):
  1890. """
  1891. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1892. ``self.defaults``.
  1893. :return: None
  1894. """
  1895. self.report_usage("on_import_preferences")
  1896. App.log.debug("on_import_preferences()")
  1897. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1898. try:
  1899. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1900. directory=self.data_path, filter=filter)
  1901. except TypeError:
  1902. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  1903. filename = str(filename)
  1904. if filename == "":
  1905. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences import cancelled."))
  1906. else:
  1907. try:
  1908. f = open(filename)
  1909. options = f.read()
  1910. f.close()
  1911. except IOError:
  1912. self.log.error("Could not load defaults file.")
  1913. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  1914. return
  1915. try:
  1916. defaults_from_file = json.loads(options)
  1917. except:
  1918. e = sys.exc_info()[0]
  1919. App.log.error(str(e))
  1920. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  1921. return
  1922. self.defaults.update(defaults_from_file)
  1923. self.inform.emit(_("[success]Imported Defaults from %s") %filename)
  1924. def on_export_preferences(self):
  1925. self.report_usage("on_export_preferences")
  1926. App.log.debug("on_export_preferences()")
  1927. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1928. try:
  1929. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  1930. caption=_("Export FlatCAM Preferences"),
  1931. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1932. )
  1933. except TypeError:
  1934. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  1935. filename = str(filename)
  1936. defaults_from_file = {}
  1937. if filename == "":
  1938. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences export cancelled."))
  1939. return
  1940. else:
  1941. try:
  1942. f = open(filename, 'w')
  1943. defaults_file_content = f.read()
  1944. f.close()
  1945. except IOError:
  1946. App.log.debug('Creating a new preferences file ...')
  1947. f = open(filename, 'w')
  1948. json.dump({}, f)
  1949. f.close()
  1950. except:
  1951. e = sys.exc_info()[0]
  1952. App.log.error("Could not load defaults file.")
  1953. App.log.error(str(e))
  1954. self.inform.emit(_("[ERROR_NOTCL]Could not load defaults file."))
  1955. return
  1956. try:
  1957. defaults_from_file = json.loads(defaults_file_content)
  1958. except:
  1959. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1960. # Update options
  1961. self.defaults_read_form()
  1962. defaults_from_file.update(self.defaults)
  1963. self.propagate_defaults(silent=True)
  1964. # Save update options
  1965. try:
  1966. f = open(filename, "w")
  1967. json.dump(defaults_from_file, f)
  1968. f.close()
  1969. except:
  1970. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  1971. return
  1972. self.file_saved.emit("preferences", filename)
  1973. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1974. def on_preferences_open_folder(self):
  1975. self.report_usage("on_preferences_open_folder()")
  1976. if sys.platform == 'win32':
  1977. subprocess.Popen('explorer %s' % self.data_path)
  1978. elif sys.platform == 'darwin':
  1979. os.system('open "%s"' % self.data_path)
  1980. else:
  1981. subprocess.Popen(['xdg-open', self.data_path])
  1982. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1983. def save_geometry(self, x, y, width, height, notebook_width):
  1984. self.defaults["global_def_win_x"] = x
  1985. self.defaults["global_def_win_y"] = y
  1986. self.defaults["global_def_win_w"] = width
  1987. self.defaults["global_def_win_h"] = height
  1988. self.defaults["def_notebook_width"] = notebook_width
  1989. self.save_defaults()
  1990. def message_dialog(self, title, message, kind="info"):
  1991. icon = {"info": QtWidgets.QMessageBox.Information,
  1992. "warning": QtWidgets.QMessageBox.Warning,
  1993. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1994. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1995. dlg.setText(message)
  1996. dlg.exec_()
  1997. def register_recent(self, kind, filename):
  1998. self.log.debug("register_recent()")
  1999. self.log.debug(" %s" % kind)
  2000. self.log.debug(" %s" % filename)
  2001. record = {'kind': str(kind), 'filename': str(filename)}
  2002. if record in self.recent:
  2003. return
  2004. self.recent.insert(0, record)
  2005. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2006. self.recent.pop()
  2007. try:
  2008. f = open(self.data_path + '/recent.json', 'w')
  2009. except IOError:
  2010. App.log.error("Failed to open recent items file for writing.")
  2011. self.inform.emit(_('[ERROR_NOTCL]Failed to open recent files file for writing.'))
  2012. return
  2013. #try:
  2014. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2015. # except:
  2016. # App.log.error("Failed to write to recent items file.")
  2017. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2018. # f.close()
  2019. f.close()
  2020. # Re-buid the recent items menu
  2021. self.setup_recent_items()
  2022. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2023. """
  2024. Creates a new specalized FlatCAMObj and attaches it to the application,
  2025. this is, updates the GUI accordingly, any other records and plots it.
  2026. This method is thread-safe.
  2027. Notes:
  2028. * If the name is in use, the self.collection will modify it
  2029. when appending it to the collection. There is no need to handle
  2030. name conflicts here.
  2031. :param kind: The kind of object to create. One of 'gerber',
  2032. 'excellon', 'cncjob' and 'geometry'.
  2033. :type kind: str
  2034. :param name: Name for the object.
  2035. :type name: str
  2036. :param initialize: Function to run after creation of the object
  2037. but before it is attached to the application. The function is
  2038. called with 2 parameters: the new object and the App instance.
  2039. :type initialize: function
  2040. :return: None
  2041. :rtype: None
  2042. """
  2043. App.log.debug("new_object()")
  2044. obj_plot = plot
  2045. obj_autoselected = autoselected
  2046. t0 = time.time() # Debug
  2047. ## Create object
  2048. classdict = {
  2049. "gerber": FlatCAMGerber,
  2050. "excellon": FlatCAMExcellon,
  2051. "cncjob": FlatCAMCNCjob,
  2052. "geometry": FlatCAMGeometry
  2053. }
  2054. App.log.debug("Calling object constructor...")
  2055. obj = classdict[kind](name)
  2056. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2057. # Set options from "Project options" form
  2058. self.options_read_form()
  2059. # IMPORTANT
  2060. # The key names in defaults and options dictionary's are not random:
  2061. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2062. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2063. # the options from project options form into the self.options. After that, below, depending on the type of
  2064. # object that is created, it will strip the name of the object and the underline (if the original key was
  2065. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2066. # "toolchange"
  2067. for option in self.options:
  2068. if option.find(kind + "_") == 0:
  2069. oname = option[len(kind) + 1:]
  2070. obj.options[oname] = self.options[option]
  2071. obj.isHovering = False
  2072. obj.notHovering = True
  2073. # Initialize as per user request
  2074. # User must take care to implement initialize
  2075. # in a thread-safe way as is is likely that we
  2076. # have been invoked in a separate thread.
  2077. t1 = time.time()
  2078. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2079. try:
  2080. return_value = initialize(obj, self)
  2081. except Exception as e:
  2082. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2083. msg += _("Object (%s) failed because: %s \n\n") % (kind, str(e))
  2084. msg += traceback.format_exc()
  2085. self.inform.emit(msg)
  2086. # if str(e) == "Empty Geometry":
  2087. # self.inform.emit("[ERROR_NOTCL] )
  2088. # else:
  2089. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2090. return "fail"
  2091. t2 = time.time()
  2092. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2093. if return_value == 'fail':
  2094. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2095. return "fail"
  2096. # Check units and convert if necessary
  2097. # This condition CAN be true because initialize() can change obj.units
  2098. if self.options["units"].upper() != obj.units.upper():
  2099. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2100. obj.convert_units(self.options["units"])
  2101. t3 = time.time()
  2102. self.log.debug("%f seconds converting units." % (t3 - t2))
  2103. # Create the bounding box for the object and then add the results to the obj.options
  2104. try:
  2105. xmin, ymin, xmax, ymax = obj.bounds()
  2106. obj.options['xmin'] = xmin
  2107. obj.options['ymin'] = ymin
  2108. obj.options['xmax'] = xmax
  2109. obj.options['ymax'] = ymax
  2110. except:
  2111. log.warning("The object has no bounds properties.")
  2112. # don't plot objects with no bounds, there is nothing to plot
  2113. self.plot = False
  2114. pass
  2115. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2116. # Move the object to the main thread and let the app know that it is available.
  2117. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2118. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2119. return obj
  2120. def new_excellon_object(self):
  2121. self.report_usage("new_excellon_object()")
  2122. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2123. def new_geometry_object(self):
  2124. self.report_usage("new_geometry_object()")
  2125. def initialize(obj, self):
  2126. obj.multitool = False
  2127. self.new_object('geometry', 'new_g', initialize, plot=False)
  2128. def on_object_created(self, obj, plot, autoselect):
  2129. """
  2130. Event callback for object creation.
  2131. :param obj: The newly created FlatCAM object.
  2132. :return: None
  2133. """
  2134. t0 = time.time() # DEBUG
  2135. self.log.debug("on_object_created()")
  2136. # The Collection might change the name if there is a collision
  2137. self.collection.append(obj)
  2138. # after adding the object to the collection always update the list of objects that are in the collection
  2139. self.all_objects_list = self.collection.get_list()
  2140. # self.inform.emit('[selected] %s created & selected: %s' %
  2141. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2142. if obj.kind == 'gerber':
  2143. self.inform.emit('_([selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2144. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  2145. elif obj.kind == 'excellon':
  2146. self.inform.emit(_('[selected]%s created/selected: <span style="color:%s;">%s</span>') %
  2147. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  2148. elif obj.kind == 'cncjob':
  2149. self.inform.emit(_('[selected]%s created/selected: <span style="color:%s;">%s</span>') %
  2150. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  2151. elif obj.kind == 'geometry':
  2152. self.inform.emit(_('[selected]%s created/selected: <span style="color:%s;">%s</span>') %
  2153. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  2154. # update the SHELL auto-completer model with the name of the new object
  2155. self.myKeywords.append(obj.options['name'])
  2156. self.shell._edit.set_model_data(self.myKeywords)
  2157. if autoselect:
  2158. # select the just opened object but deselect the previous ones
  2159. self.collection.set_all_inactive()
  2160. self.collection.set_active(obj.options["name"])
  2161. # here it is done the object plotting
  2162. def worker_task(obj):
  2163. with self.proc_container.new("Plotting"):
  2164. if isinstance(obj, FlatCAMCNCjob):
  2165. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2166. else:
  2167. obj.plot()
  2168. t1 = time.time() # DEBUG
  2169. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2170. self.object_plotted.emit(obj)
  2171. # Send to worker
  2172. # self.worker.add_task(worker_task, [self])
  2173. if plot is True:
  2174. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2175. def on_object_changed(self, obj):
  2176. # update the bounding box data from obj.options
  2177. xmin, ymin, xmax, ymax = obj.bounds()
  2178. obj.options['xmin'] = xmin
  2179. obj.options['ymin'] = ymin
  2180. obj.options['xmax'] = xmax
  2181. obj.options['ymax'] = ymax
  2182. log.debug("Object changed, updating the bounding box data on self.options")
  2183. # delete the old selection shape
  2184. self.delete_selection_shape()
  2185. self.should_we_save = True
  2186. def on_object_plotted(self, obj):
  2187. self.on_zoom_fit(None)
  2188. def options_read_form(self):
  2189. for option in self.options_form_fields:
  2190. self.options[option] = self.options_form_fields[option].get_value()
  2191. def options_write_form(self):
  2192. for option in self.options:
  2193. self.options_write_form_field(option)
  2194. def options_write_form_field(self, field):
  2195. try:
  2196. self.options_form_fields[field].set_value(self.options[field])
  2197. except KeyError:
  2198. # Changed from error to debug. This allows to have data stored
  2199. # which is not user-editable.
  2200. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2201. pass
  2202. def on_about(self):
  2203. """
  2204. Displays the "about" dialog.
  2205. :return: None
  2206. """
  2207. self.report_usage("on_about")
  2208. version = self.version
  2209. version_date = self.version_date
  2210. beta = self.beta
  2211. class AboutDialog(QtWidgets.QDialog):
  2212. def __init__(self, parent=None):
  2213. QtWidgets.QDialog.__init__(self, parent)
  2214. # Icon and title
  2215. self.setWindowIcon(parent.app_icon)
  2216. self.setWindowTitle("FlatCAM")
  2217. layout1 = QtWidgets.QVBoxLayout()
  2218. self.setLayout(layout1)
  2219. layout2 = QtWidgets.QHBoxLayout()
  2220. layout1.addLayout(layout2)
  2221. logo = QtWidgets.QLabel()
  2222. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2223. layout2.addWidget(logo, stretch=0)
  2224. title = QtWidgets.QLabel(
  2225. "<font size=8><B>FlatCAM</B></font><BR>"
  2226. "Version %s %s (%s) - %s <BR>"
  2227. "<BR>"
  2228. "2D Computer-Aided Printed Circuit Board<BR>"
  2229. "Manufacturing.<BR>"
  2230. "<BR>"
  2231. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2232. "<BR>"
  2233. "<B> Main Contributors:</B><BR>"
  2234. "Denis Hayrullin<BR>"
  2235. "Kamil Sopko<BR>"
  2236. "Marius Stanciu<BR>"
  2237. "Matthieu Berthomé<BR>"
  2238. "and many others found "
  2239. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2240. "<BR>"
  2241. "Development is done "
  2242. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2243. "DOWNLOAD area "
  2244. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2245. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2246. )
  2247. title.setOpenExternalLinks(True)
  2248. layout2.addWidget(title, stretch=1)
  2249. layout3 = QtWidgets.QHBoxLayout()
  2250. layout1.addLayout(layout3)
  2251. layout3.addStretch()
  2252. okbtn = QtWidgets.QPushButton("Close")
  2253. layout3.addWidget(okbtn)
  2254. okbtn.clicked.connect(self.accept)
  2255. AboutDialog(self.ui).exec_()
  2256. def on_file_savedefaults(self):
  2257. """
  2258. Callback for menu item File->Save Defaults. Saves application default options
  2259. ``self.defaults`` to current_defaults.FlatConfig.
  2260. :return: None
  2261. """
  2262. self.save_defaults()
  2263. def on_app_exit(self):
  2264. self.report_usage("on_app_exit()")
  2265. if self.collection.get_list():
  2266. msgbox = QtWidgets.QMessageBox()
  2267. # msgbox.setText("<B>Save changes ...</B>")
  2268. msgbox.setText("There are files/objects opened in FlatCAM. "
  2269. "\n"
  2270. "Do you want to Save the project?")
  2271. msgbox.setWindowTitle("Save changes")
  2272. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2273. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2274. QtWidgets.QMessageBox.Cancel)
  2275. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2276. response = msgbox.exec_()
  2277. if response == QtWidgets.QMessageBox.Yes:
  2278. self.on_file_saveprojectas(thread=False)
  2279. elif response == QtWidgets.QMessageBox.Cancel:
  2280. return
  2281. self.save_defaults()
  2282. else:
  2283. self.save_defaults()
  2284. log.debug("Application defaults saved ... Exit event.")
  2285. QtWidgets.qApp.quit()
  2286. def save_defaults(self, silent=False):
  2287. """
  2288. Saves application default options
  2289. ``self.defaults`` to current_defaults.FlatConfig.
  2290. :return: None
  2291. """
  2292. self.report_usage("save_defaults")
  2293. # Read options from file
  2294. try:
  2295. f = open(self.data_path + "/current_defaults.FlatConfig")
  2296. defaults_file_content = f.read()
  2297. f.close()
  2298. except:
  2299. e = sys.exc_info()[0]
  2300. App.log.error("Could not load defaults file.")
  2301. App.log.error(str(e))
  2302. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2303. return
  2304. try:
  2305. defaults = json.loads(defaults_file_content)
  2306. except:
  2307. e = sys.exc_info()[0]
  2308. App.log.error("Failed to parse defaults file.")
  2309. App.log.error(str(e))
  2310. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2311. return
  2312. # Update options
  2313. self.defaults_read_form()
  2314. defaults.update(self.defaults)
  2315. self.propagate_defaults(silent=True)
  2316. # Save update options
  2317. try:
  2318. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2319. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2320. f.close()
  2321. except:
  2322. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2323. return
  2324. # Save the toolbar view
  2325. tb_status = 0
  2326. if self.ui.toolbarfile.isVisible():
  2327. tb_status += 1
  2328. if self.ui.toolbargeo.isVisible():
  2329. tb_status += 2
  2330. if self.ui.toolbarview.isVisible():
  2331. tb_status += 4
  2332. if self.ui.toolbartools.isVisible():
  2333. tb_status += 8
  2334. if self.ui.exc_edit_toolbar.isVisible():
  2335. tb_status += 16
  2336. if self.ui.geo_edit_toolbar.isVisible():
  2337. tb_status += 32
  2338. if self.ui.snap_toolbar.isVisible():
  2339. tb_status += 64
  2340. if self.ui.toolbarshell.isVisible():
  2341. tb_status += 128
  2342. self.defaults["global_toolbar_view"] = tb_status
  2343. if not silent:
  2344. self.inform.emit(_("[success]Defaults saved."))
  2345. def save_factory_defaults(self, silent=False):
  2346. """
  2347. Saves application factory default options
  2348. ``self.defaults`` to factory_defaults.FlatConfig.
  2349. It's a one time job done just after the first install.
  2350. :return: None
  2351. """
  2352. self.report_usage("save_factory_defaults")
  2353. # Read options from file
  2354. try:
  2355. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2356. factory_defaults_file_content = f_f_def.read()
  2357. f_f_def.close()
  2358. except:
  2359. e = sys.exc_info()[0]
  2360. App.log.error("Could not load factory defaults file.")
  2361. App.log.error(str(e))
  2362. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2363. return
  2364. try:
  2365. factory_defaults = json.loads(factory_defaults_file_content)
  2366. except:
  2367. e = sys.exc_info()[0]
  2368. App.log.error("Failed to parse factory defaults file.")
  2369. App.log.error(str(e))
  2370. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2371. return
  2372. # Update options
  2373. self.defaults_read_form()
  2374. factory_defaults.update(self.defaults)
  2375. self.propagate_defaults(silent=True)
  2376. # Save update options
  2377. try:
  2378. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2379. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2380. f_f_def_s.close()
  2381. except:
  2382. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2383. return
  2384. if silent is False:
  2385. self.inform.emit(_("Factory defaults saved."))
  2386. def final_save(self):
  2387. if self.should_we_save and self.collection.get_list():
  2388. msgbox = QtWidgets.QMessageBox()
  2389. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2390. "\n"
  2391. "Do you want to Save the project?"))
  2392. msgbox.setWindowTitle(_("Save changes"))
  2393. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2394. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2395. QtWidgets.QMessageBox.Cancel)
  2396. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2397. response = msgbox.exec_()
  2398. if response == QtWidgets.QMessageBox.Yes:
  2399. self.on_file_saveprojectas(thread=False)
  2400. elif response == QtWidgets.QMessageBox.Cancel:
  2401. self.should_we_quit = False
  2402. return
  2403. self.save_defaults()
  2404. log.debug("App.final_save() --> App Defaults saved.")
  2405. # save toolbar state to file
  2406. settings = QSettings("Open Source", "FlatCAM")
  2407. settings.setValue('saved_gui_state', self.ui.saveState())
  2408. settings.setValue('maximized_gui', self.ui.isMaximized())
  2409. # This will write the setting to the platform specific storage.
  2410. del settings
  2411. log.debug("App.final_save() --> App UI state saved.")
  2412. QtWidgets.qApp.quit()
  2413. def on_toggle_shell(self):
  2414. """
  2415. toggle shell if is visible close it if closed open it
  2416. :return:
  2417. """
  2418. self.report_usage("on_toggle_shell()")
  2419. if self.ui.shell_dock.isVisible():
  2420. self.ui.shell_dock.hide()
  2421. else:
  2422. self.ui.shell_dock.show()
  2423. def on_edit_join(self, name=None):
  2424. """
  2425. Callback for Edit->Join. Joins the selected geometry objects into
  2426. a new one.
  2427. :return: None
  2428. """
  2429. self.report_usage("on_edit_join()")
  2430. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2431. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2432. tooldias = []
  2433. geo_type_list = []
  2434. objs = self.collection.get_selected()
  2435. for obj in objs:
  2436. geo_type_list.append(obj.multigeo)
  2437. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2438. if len(set(geo_type_list)) != 1:
  2439. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2440. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2441. "convert from one to another and retry joining \n"
  2442. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2443. "the result may not be what was expected. \n"
  2444. "Check the generated GCODE."))
  2445. return
  2446. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2447. if True in geo_type_list:
  2448. def initialize(obj, app):
  2449. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2450. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2451. for v in obj.tools.values():
  2452. v['data']['name'] = obj_name_multi
  2453. self.new_object("geometry", obj_name_multi, initialize)
  2454. else:
  2455. def initialize(obj, app):
  2456. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2457. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2458. for v in obj.tools.values():
  2459. v['data']['name'] = obj_name_single
  2460. self.new_object("geometry", obj_name_single, initialize)
  2461. self.should_we_save = True
  2462. def on_edit_join_exc(self):
  2463. """
  2464. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2465. a new one.
  2466. :return: None
  2467. """
  2468. self.report_usage("on_edit_join_exc()")
  2469. objs = self.collection.get_selected()
  2470. for obj in objs:
  2471. if not isinstance(obj, FlatCAMExcellon):
  2472. self.inform.emit(_("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects."))
  2473. return
  2474. def initialize(obj, app):
  2475. FlatCAMExcellon.merge(objs, obj)
  2476. self.new_object("excellon", 'Combo_Excellon', initialize)
  2477. self.should_we_save = True
  2478. def on_edit_join_grb(self):
  2479. """
  2480. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2481. a new one.
  2482. :return: None
  2483. """
  2484. self.report_usage("on_edit_join_grb()")
  2485. objs = self.collection.get_selected()
  2486. for obj in objs:
  2487. if not isinstance(obj, FlatCAMGerber):
  2488. self.inform.emit(_("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects."))
  2489. return
  2490. def initialize(obj, app):
  2491. FlatCAMGerber.merge(objs, obj)
  2492. self.new_object("gerber", 'Combo_Gerber', initialize)
  2493. self.should_we_save = True
  2494. def on_convert_singlegeo_to_multigeo(self):
  2495. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2496. obj = self.collection.get_active()
  2497. if obj is None:
  2498. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2499. return
  2500. if not isinstance(obj, FlatCAMGeometry):
  2501. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2502. return
  2503. obj.multigeo = True
  2504. for tooluid, dict_value in obj.tools.items():
  2505. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2506. if not isinstance(obj.solid_geometry, list):
  2507. obj.solid_geometry = [obj.solid_geometry]
  2508. obj.solid_geometry[:] = []
  2509. obj.plot()
  2510. self.should_we_save = True
  2511. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2512. def on_convert_multigeo_to_singlegeo(self):
  2513. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2514. obj = self.collection.get_active()
  2515. if obj is None:
  2516. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2517. return
  2518. if not isinstance(obj, FlatCAMGeometry):
  2519. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2520. return
  2521. obj.multigeo = False
  2522. total_solid_geometry = []
  2523. for tooluid, dict_value in obj.tools.items():
  2524. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2525. # clear the original geometry
  2526. dict_value['solid_geometry'][:] = []
  2527. obj.solid_geometry = deepcopy(total_solid_geometry)
  2528. obj.plot()
  2529. self.should_we_save = True
  2530. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2531. def on_options_dict_change(self, field):
  2532. self.options_write_form_field(field)
  2533. if field == "units":
  2534. self.set_screen_units(self.options['units'])
  2535. def on_defaults_dict_change(self, field):
  2536. self.defaults_write_form_field(field)
  2537. if field == "units":
  2538. self.set_screen_units(self.defaults['units'])
  2539. def set_screen_units(self, units):
  2540. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2541. def on_toggle_units(self):
  2542. """
  2543. Callback for the Units radio-button change in the Options tab.
  2544. Changes the application's default units or the current project's units.
  2545. If changing the project's units, the change propagates to all of
  2546. the objects in the project.
  2547. :return: None
  2548. """
  2549. self.report_usage("on_toggle_units")
  2550. if self.toggle_units_ignore:
  2551. return
  2552. # If option is the same, then ignore
  2553. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2554. self.defaults["units"].upper():
  2555. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2556. return
  2557. # Options to scale
  2558. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2559. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2560. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2561. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2562. "excellon_z_pdepth",
  2563. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2564. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2565. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2566. "geometry_feedrate_probe",
  2567. 'cncjob_tooldia',
  2568. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2569. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2570. "tools_2sided_drilldia", "tools_film_boundary",
  2571. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2572. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2573. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2574. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2575. "tools_transform_offset_y",
  2576. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2577. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2578. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2579. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2580. 'global_gridx', 'global_gridy', 'global_snap_max']
  2581. def scale_options(sfactor):
  2582. for dim in dimensions:
  2583. if dim == 'excellon_toolchangexy':
  2584. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2585. coords_xy[0] *= sfactor
  2586. coords_xy[1] *= sfactor
  2587. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2588. elif dim == 'geometry_toolchangexy':
  2589. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2590. coords_xy[0] *= sfactor
  2591. coords_xy[1] *= sfactor
  2592. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2593. elif dim == 'tools_ncctools':
  2594. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2595. ncctols[0] *= sfactor
  2596. ncctols[1] *= sfactor
  2597. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2598. elif dim == 'tools_solderpaste_tools':
  2599. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2600. sp_tools[0] *= sfactor
  2601. sp_tools[1] *= sfactor
  2602. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2603. elif dim == 'tools_solderpaste_xy_toolchange':
  2604. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2605. sp_coords[0] *= sfactor
  2606. sp_coords[1] *= sfactor
  2607. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2608. else:
  2609. try:
  2610. self.options[dim] = float(self.options[dim]) * sfactor
  2611. except Exception as e:
  2612. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2613. def scale_defaults(sfactor):
  2614. for dim in dimensions:
  2615. if dim == 'excellon_toolchangexy':
  2616. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2617. coords_xy[0] *= sfactor
  2618. coords_xy[1] *= sfactor
  2619. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2620. elif dim == 'geometry_toolchangexy':
  2621. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2622. coords_xy[0] *= sfactor
  2623. coords_xy[1] *= sfactor
  2624. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2625. elif dim == 'tools_ncctools':
  2626. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2627. ncctols[0] *= sfactor
  2628. ncctols[1] *= sfactor
  2629. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2630. elif dim == 'tools_solderpaste_tools':
  2631. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2632. sp_tools[0] *= sfactor
  2633. sp_tools[1] *= sfactor
  2634. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2635. elif dim == 'tools_solderpaste_xy_toolchange':
  2636. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2637. sp_coords[0] *= sfactor
  2638. sp_coords[1] *= sfactor
  2639. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2640. else:
  2641. try:
  2642. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  2643. except Exception as e:
  2644. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  2645. # The scaling factor depending on choice of units.
  2646. factor = 1/25.4
  2647. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2648. factor = 25.4
  2649. # Changing project units. Warn user.
  2650. msgbox = QtWidgets.QMessageBox()
  2651. msgbox.setText("<B>Change project units ...</B>")
  2652. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2653. "properties of all objects to be scaled accordingly. Continue?")
  2654. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2655. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2656. response = msgbox.exec_()
  2657. if response == QtWidgets.QMessageBox.Ok:
  2658. self.options_read_form()
  2659. scale_options(factor)
  2660. self.options_write_form()
  2661. self.defaults_read_form()
  2662. scale_defaults(factor)
  2663. self.defaults_write_form()
  2664. self.should_we_save = True
  2665. # change this only if the workspace is active
  2666. if self.defaults['global_workspace'] is True:
  2667. self.plotcanvas.draw_workspace()
  2668. # adjust the grid values on the main toolbar
  2669. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2670. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2671. for obj in self.collection.get_list():
  2672. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2673. obj.convert_units(units)
  2674. # make that the properties stored in the object are also updated
  2675. self.object_changed.emit(obj)
  2676. obj.build_ui()
  2677. current = self.collection.get_active()
  2678. if current is not None:
  2679. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2680. if not isinstance(current, FlatCAMGeometry):
  2681. current.to_form()
  2682. self.plot_all()
  2683. self.inform.emit(_("[success]Converted units to %s") % self.defaults["units"])
  2684. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2685. self.set_screen_units(self.defaults["units"])
  2686. else:
  2687. # Undo toggling
  2688. self.toggle_units_ignore = True
  2689. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2690. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  2691. else:
  2692. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  2693. self.toggle_units_ignore = False
  2694. self.inform.emit(_("[WARNING_NOTCL]Units conversion cancelled."))
  2695. self.options_read_form()
  2696. self.defaults_read_form()
  2697. def on_toggle_units_click(self):
  2698. if self.options["units"] == 'MM':
  2699. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  2700. else:
  2701. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  2702. self.on_toggle_units()
  2703. def on_fullscreen(self):
  2704. self.report_usage("on_fullscreen()")
  2705. if self.toggle_fscreen is False:
  2706. if sys.platform == 'win32':
  2707. self.ui.showFullScreen()
  2708. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2709. tb.setVisible(False)
  2710. self.ui.splitter_left.setVisible(False)
  2711. self.toggle_fscreen = True
  2712. else:
  2713. if sys.platform == 'win32':
  2714. self.ui.showNormal()
  2715. self.restore_toolbar_view()
  2716. self.ui.splitter_left.setVisible(True)
  2717. self.toggle_fscreen = False
  2718. def on_toggle_plotarea(self):
  2719. self.report_usage("on_toggle_plotarea()")
  2720. try:
  2721. name = self.ui.plot_tab_area.widget(0).objectName()
  2722. except AttributeError:
  2723. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2724. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2725. self.ui.plot_tab_area.protectTab(0)
  2726. return
  2727. if name != 'plotarea':
  2728. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2729. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2730. self.ui.plot_tab_area.protectTab(0)
  2731. else:
  2732. self.ui.plot_tab_area.closeTab(0)
  2733. def on_toggle_notebook(self):
  2734. if self.ui.splitter.sizes()[0] == 0:
  2735. self.ui.splitter.setSizes([1, 1])
  2736. else:
  2737. self.ui.splitter.setSizes([0, 1])
  2738. def on_toggle_axis(self):
  2739. self.report_usage("on_toggle_axis()")
  2740. if self.toggle_axis is False:
  2741. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2742. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2743. self.plotcanvas.redraw()
  2744. self.toggle_axis = True
  2745. else:
  2746. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2747. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2748. self.plotcanvas.redraw()
  2749. self.toggle_axis = False
  2750. def on_toggle_grid(self):
  2751. self.report_usage("on_toggle_grid()")
  2752. self.ui.grid_snap_btn.trigger()
  2753. def on_toggle_code_editor(self):
  2754. self.report_usage("on_toggle_code_editor()")
  2755. if self.toggle_codeeditor is False:
  2756. # add the tab if it was closed
  2757. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  2758. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  2759. # first clear previous text in text editor (if any)
  2760. self.ui.code_editor.clear()
  2761. # Switch plot_area to CNCJob tab
  2762. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  2763. self.toggle_codeeditor = True
  2764. else:
  2765. for idx in range(self.ui.plot_tab_area.count()):
  2766. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  2767. self.ui.plot_tab_area.closeTab(idx)
  2768. break
  2769. self.toggle_codeeditor = False
  2770. def on_options_combo_change(self, sel):
  2771. """
  2772. Called when the combo box to choose between application defaults and
  2773. project option changes value. The corresponding variables are
  2774. copied to the UI.
  2775. :param sel: The option index that was chosen.
  2776. :return: None
  2777. """
  2778. # combo_sel = self.ui.notebook.combo_options.get_active()
  2779. App.log.debug("Options --> %s" % sel)
  2780. # form = [self.defaults_form, self.options_form][sel]
  2781. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2782. if sel == 0:
  2783. self.gen_form = self.ui.general_defaults_form
  2784. self.ger_form = self.ui.gerber_defaults_form
  2785. self.exc_form = self.ui.excellon_defaults_form
  2786. self.geo_form = self.ui.geometry_defaults_form
  2787. self.cnc_form = self.ui.cncjob_defaults_form
  2788. self.tools_form = self.ui.tools_defaults_form
  2789. elif sel == 1:
  2790. self.gen_form = self.ui.general_options_form
  2791. self.ger_form = self.ui.gerber_options_form
  2792. self.exc_form = self.ui.excellon_options_form
  2793. self.geo_form = self.ui.geometry_options_form
  2794. self.cnc_form = self.ui.cncjob_options_form
  2795. self.tools_form = self.ui.tools_options_form
  2796. else:
  2797. return
  2798. try:
  2799. self.ui.general_scroll_area.takeWidget()
  2800. except:
  2801. self.log.debug("Nothing to remove")
  2802. self.ui.general_scroll_area.setWidget(self.gen_form)
  2803. self.gen_form.show()
  2804. try:
  2805. self.ui.gerber_scroll_area.takeWidget()
  2806. except:
  2807. self.log.debug("Nothing to remove")
  2808. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2809. self.ger_form.show()
  2810. try:
  2811. self.ui.excellon_scroll_area.takeWidget()
  2812. except:
  2813. self.log.debug("Nothing to remove")
  2814. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2815. self.exc_form.show()
  2816. try:
  2817. self.ui.geometry_scroll_area.takeWidget()
  2818. except:
  2819. self.log.debug("Nothing to remove")
  2820. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2821. self.geo_form.show()
  2822. try:
  2823. self.ui.cncjob_scroll_area.takeWidget()
  2824. except:
  2825. self.log.debug("Nothing to remove")
  2826. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2827. self.cnc_form.show()
  2828. try:
  2829. self.ui.tools_scroll_area.takeWidget()
  2830. except:
  2831. self.log.debug("Nothing to remove")
  2832. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2833. self.tools_form.show()
  2834. self.log.debug("Finished GUI form initialization.")
  2835. # self.options2form()
  2836. def on_excellon_defaults_button(self):
  2837. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2838. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2839. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2840. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2841. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2842. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2843. log.debug("Excellon app defaults loaded ...")
  2844. def on_excellon_options_button(self):
  2845. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2846. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2847. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2848. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2849. self.options_form_fields["excellon_zeros"].set_value('L')
  2850. self.options_form_fields["excellon_units"].set_value('INCH')
  2851. log.debug("Excellon options defaults loaded ...")
  2852. # Setting plot colors handlers
  2853. def on_pf_color_entry(self):
  2854. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2855. self.defaults['global_plot_fill'][7:9]
  2856. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2857. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2858. def on_pf_color_button(self):
  2859. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2860. c_dialog = QtWidgets.QColorDialog()
  2861. plot_fill_color = c_dialog.getColor(initial=current_color)
  2862. if plot_fill_color.isValid() is False:
  2863. return
  2864. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2865. "background-color:%s" % str(plot_fill_color.name()))
  2866. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2867. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2868. self.defaults['global_plot_fill'] = new_val
  2869. def on_pf_color_spinner(self):
  2870. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2871. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2872. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2873. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2874. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2875. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2876. def on_pf_color_slider(self):
  2877. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2878. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2879. def on_pl_color_entry(self):
  2880. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2881. self.defaults['global_plot_line'][7:9]
  2882. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2883. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2884. def on_pl_color_button(self):
  2885. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2886. # print(current_color)
  2887. c_dialog = QtWidgets.QColorDialog()
  2888. plot_line_color = c_dialog.getColor(initial=current_color)
  2889. if plot_line_color.isValid() is False:
  2890. return
  2891. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2892. "background-color:%s" % str(plot_line_color.name()))
  2893. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2894. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2895. self.defaults['global_plot_line'] = new_val_line
  2896. # Setting selection colors (left - right) handlers
  2897. def on_sf_color_entry(self):
  2898. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2899. self.defaults['global_sel_fill'][7:9]
  2900. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2901. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2902. def on_sf_color_button(self):
  2903. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2904. c_dialog = QtWidgets.QColorDialog()
  2905. plot_fill_color = c_dialog.getColor(initial=current_color)
  2906. if plot_fill_color.isValid() is False:
  2907. return
  2908. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2909. "background-color:%s" % str(plot_fill_color.name()))
  2910. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2911. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2912. self.defaults['global_sel_fill'] = new_val
  2913. def on_sf_color_spinner(self):
  2914. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2915. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2916. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2917. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2918. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2919. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2920. def on_sf_color_slider(self):
  2921. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2922. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2923. def on_sl_color_entry(self):
  2924. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2925. self.defaults['global_sel_line'][7:9]
  2926. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2927. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2928. def on_sl_color_button(self):
  2929. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2930. c_dialog = QtWidgets.QColorDialog()
  2931. plot_line_color = c_dialog.getColor(initial=current_color)
  2932. if plot_line_color.isValid() is False:
  2933. return
  2934. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2935. "background-color:%s" % str(plot_line_color.name()))
  2936. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2937. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2938. self.defaults['global_sel_line'] = new_val_line
  2939. # Setting selection colors (right - left) handlers
  2940. def on_alt_sf_color_entry(self):
  2941. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  2942. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2943. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2944. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2945. def on_alt_sf_color_button(self):
  2946. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2947. c_dialog = QtWidgets.QColorDialog()
  2948. plot_fill_color = c_dialog.getColor(initial=current_color)
  2949. if plot_fill_color.isValid() is False:
  2950. return
  2951. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2952. "background-color:%s" % str(plot_fill_color.name()))
  2953. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2954. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2955. self.defaults['global_alt_sel_fill'] = new_val
  2956. def on_alt_sf_color_spinner(self):
  2957. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2958. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2959. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2960. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2961. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2962. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2963. def on_alt_sf_color_slider(self):
  2964. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2965. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2966. def on_alt_sl_color_entry(self):
  2967. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  2968. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2969. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2970. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2971. def on_alt_sl_color_button(self):
  2972. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2973. c_dialog = QtWidgets.QColorDialog()
  2974. plot_line_color = c_dialog.getColor(initial=current_color)
  2975. if plot_line_color.isValid() is False:
  2976. return
  2977. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2978. "background-color:%s" % str(plot_line_color.name()))
  2979. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2980. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2981. self.defaults['global_alt_sel_line'] = new_val_line
  2982. # Setting Editor colors
  2983. def on_draw_color_entry(self):
  2984. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2985. .draw_color_entry.get_value()
  2986. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2987. "background-color:%s" % str(self.defaults['global_draw_color']))
  2988. def on_draw_color_button(self):
  2989. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2990. c_dialog = QtWidgets.QColorDialog()
  2991. draw_color = c_dialog.getColor(initial=current_color)
  2992. if draw_color.isValid() is False:
  2993. return
  2994. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2995. "background-color:%s" % str(draw_color.name()))
  2996. new_val = str(draw_color.name())
  2997. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2998. self.defaults['global_draw_color'] = new_val
  2999. def on_sel_draw_color_entry(self):
  3000. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3001. .sel_draw_color_entry.get_value()
  3002. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3003. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3004. def on_sel_draw_color_button(self):
  3005. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3006. c_dialog = QtWidgets.QColorDialog()
  3007. sel_draw_color = c_dialog.getColor(initial=current_color)
  3008. if sel_draw_color.isValid() is False:
  3009. return
  3010. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3011. "background-color:%s" % str(sel_draw_color.name()))
  3012. new_val_sel = str(sel_draw_color.name())
  3013. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3014. self.defaults['global_sel_draw_color'] = new_val_sel
  3015. def on_deselect_all(self):
  3016. self.collection.set_all_inactive()
  3017. self.delete_selection_shape()
  3018. def on_workspace_modified(self):
  3019. self.save_defaults(silent=True)
  3020. self.plotcanvas.draw_workspace()
  3021. def on_workspace(self):
  3022. self.report_usage("on_workspace()")
  3023. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3024. self.plotcanvas.restore_workspace()
  3025. else:
  3026. self.plotcanvas.delete_workspace()
  3027. self.save_defaults(silent=True)
  3028. def on_workspace_menu(self):
  3029. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3030. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3031. else:
  3032. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3033. self.on_workspace()
  3034. def on_layout(self, index, lay=None):
  3035. self.report_usage("on_layout()")
  3036. if lay:
  3037. current_layout = lay
  3038. else:
  3039. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value().lower()
  3040. settings = QSettings("Open Source", "FlatCAM")
  3041. settings.setValue('layout', current_layout)
  3042. # This will write the setting to the platform specific storage.
  3043. del settings
  3044. # first remove the toolbars:
  3045. self.ui.removeToolBar(self.ui.toolbarfile)
  3046. self.ui.removeToolBar(self.ui.toolbargeo)
  3047. self.ui.removeToolBar(self.ui.toolbarview)
  3048. self.ui.removeToolBar(self.ui.toolbarshell)
  3049. self.ui.removeToolBar(self.ui.toolbartools)
  3050. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3051. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3052. self.ui.removeToolBar(self.ui.snap_toolbar)
  3053. self.ui.removeToolBar(self.ui.toolbarshell)
  3054. if current_layout == 'standard':
  3055. ### TOOLBAR INSTALLATION ###
  3056. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3057. self.ui.toolbarfile.setObjectName('File_TB')
  3058. self.ui.addToolBar(self.ui.toolbarfile)
  3059. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3060. self.ui.toolbargeo.setObjectName('Edit_TB')
  3061. self.ui.addToolBar(self.ui.toolbargeo)
  3062. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3063. self.ui.toolbarview.setObjectName('View_TB')
  3064. self.ui.addToolBar(self.ui.toolbarview)
  3065. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3066. self.ui.toolbarshell.setObjectName('Shell_TB')
  3067. self.ui.addToolBar(self.ui.toolbarshell)
  3068. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3069. self.ui.toolbartools.setObjectName('Tools_TB')
  3070. self.ui.addToolBar(self.ui.toolbartools)
  3071. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3072. self.ui.exc_edit_toolbar.setVisible(False)
  3073. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3074. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3075. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3076. self.ui.geo_edit_toolbar.setVisible(False)
  3077. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3078. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3079. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3080. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3081. # self.ui.snap_toolbar.setMaximumHeight(30)
  3082. self.ui.addToolBar(self.ui.snap_toolbar)
  3083. self.ui.corner_snap_btn.setVisible(False)
  3084. self.ui.snap_magnet.setVisible(False)
  3085. elif current_layout == 'compact':
  3086. ### TOOLBAR INSTALLATION ###
  3087. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3088. self.ui.toolbarfile.setObjectName('File_TB')
  3089. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3090. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3091. self.ui.toolbargeo.setObjectName('Edit_TB')
  3092. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3093. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3094. self.ui.toolbarview.setObjectName('View_TB')
  3095. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3096. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3097. self.ui.toolbarshell.setObjectName('Shell_TB')
  3098. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3099. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3100. self.ui.toolbartools.setObjectName('Tools_TB')
  3101. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3102. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3103. # self.ui.geo_edit_toolbar.setVisible(False)
  3104. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3105. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3106. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3107. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3108. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3109. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3110. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3111. self.ui.snap_toolbar.setMaximumHeight(30)
  3112. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3113. self.ui.corner_snap_btn.setVisible(True)
  3114. self.ui.snap_magnet.setVisible(True)
  3115. # add all the actions to the toolbars
  3116. self.ui.populate_toolbars()
  3117. # reconnect all the signals to the toolbar actions
  3118. self.connect_toolbar_signals()
  3119. self.ui.grid_snap_btn.setChecked(True)
  3120. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3121. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3122. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3123. self.ui.grid_gap_link_cb.setChecked(True)
  3124. def on_cnc_custom_parameters(self, signal_text):
  3125. if signal_text == 'Parameters':
  3126. return
  3127. else:
  3128. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3129. def on_save_button(self):
  3130. self.save_defaults(silent=False)
  3131. # load the defaults so they are updated into the app
  3132. self.load_defaults(filename='current_defaults')
  3133. # Re-fresh project options
  3134. self.on_options_app2project()
  3135. def handleOpen(self):
  3136. self.report_usage("handleOpen()")
  3137. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3138. "All Files (*.*)"
  3139. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  3140. caption=_('Open file'), directory=self.get_last_folder(), filter=filter_group)
  3141. if path:
  3142. file = QtCore.QFile(path)
  3143. if file.open(QtCore.QIODevice.ReadOnly):
  3144. stream = QtCore.QTextStream(file)
  3145. self.gcode_edited = stream.readAll()
  3146. self.ui.code_editor.setPlainText(self.gcode_edited)
  3147. file.close()
  3148. def handlePrint(self):
  3149. self.report_usage("handlePrint()")
  3150. dialog = QtPrintSupport.QPrintDialog()
  3151. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3152. self.ui.code_editor.document().print_(dialog.printer())
  3153. def handlePreview(self):
  3154. self.report_usage("handlePreview()")
  3155. dialog = QtPrintSupport.QPrintPreviewDialog()
  3156. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3157. dialog.exec_()
  3158. def handleTextChanged(self):
  3159. self.report_usage("handleTextChanged()")
  3160. # enable = not self.ui.code_editor.document().isEmpty()
  3161. # self.ui.buttonPrint.setEnabled(enable)
  3162. # self.ui.buttonPreview.setEnabled(enable)
  3163. pass
  3164. def handleSaveGCode(self, signal, name=None, filt=None):
  3165. self.report_usage("handleSaveGCode()")
  3166. if filt:
  3167. _filter_ = filt
  3168. else:
  3169. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3170. "All Files (*.*)"
  3171. if name:
  3172. obj_name = name
  3173. else:
  3174. try:
  3175. obj_name = self.collection.get_active().options['name']
  3176. except AttributeError:
  3177. obj_name = 'file'
  3178. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3179. try:
  3180. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3181. caption=_("Export G-Code ..."),
  3182. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3183. filter=_filter_
  3184. )[0])
  3185. except TypeError:
  3186. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3187. if filename == "":
  3188. self.inform.emit(_("[WARNING_NOTCL]Export Code cancelled."))
  3189. return
  3190. else:
  3191. try:
  3192. my_gcode = self.ui.code_editor.toPlainText()
  3193. with open(filename, 'w') as f:
  3194. for line in my_gcode:
  3195. f.write(line)
  3196. except FileNotFoundError:
  3197. self.inform.emit(_("[WARNING] No such file or directory"))
  3198. return
  3199. # Just for adding it to the recent files list.
  3200. self.file_opened.emit("cncjob", filename)
  3201. self.file_saved.emit("cncjob", filename)
  3202. self.inform.emit(_("Saved to: %s") % filename)
  3203. def handleFindGCode(self):
  3204. self.report_usage("handleFindGCode()")
  3205. flags = QtGui.QTextDocument.FindCaseSensitively
  3206. text_to_be_found = self.ui.entryFind.get_value()
  3207. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3208. if r is False:
  3209. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3210. def handleReplaceGCode(self):
  3211. self.report_usage("handleReplaceGCode()")
  3212. old = self.ui.entryFind.get_value()
  3213. new = self.ui.entryReplace.get_value()
  3214. if self.ui.sel_all_cb.isChecked():
  3215. while True:
  3216. cursor = self.ui.code_editor.textCursor()
  3217. cursor.beginEditBlock()
  3218. flags = QtGui.QTextDocument.FindCaseSensitively
  3219. # self.ui.editor is the QPlainTextEdit
  3220. r = self.ui.code_editor.find(str(old), flags)
  3221. if r:
  3222. qc = self.ui.code_editor.textCursor()
  3223. if qc.hasSelection():
  3224. qc.insertText(new)
  3225. else:
  3226. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3227. break
  3228. # Mark end of undo block
  3229. cursor.endEditBlock()
  3230. else:
  3231. cursor = self.ui.code_editor.textCursor()
  3232. cursor.beginEditBlock()
  3233. qc = self.ui.code_editor.textCursor()
  3234. if qc.hasSelection():
  3235. qc.insertText(new)
  3236. # Mark end of undo block
  3237. cursor.endEditBlock()
  3238. def on_tool_add_keypress(self):
  3239. ## Current application units in Upper Case
  3240. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3241. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3242. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3243. if notebook_widget_name == 'selected_tab':
  3244. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3245. # Tool add works for Geometry only if Advanced is True in Preferences
  3246. if self.defaults["global_app_level"] == 'a':
  3247. tool_add_popup = FCInputDialog(title="New Tool ...",
  3248. text='Enter a Tool Diameter:',
  3249. min=0.0000, max=99.9999, decimals=4)
  3250. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3251. val, ok = tool_add_popup.get_value()
  3252. if ok:
  3253. if float(val) == 0:
  3254. self.inform.emit(
  3255. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3256. return
  3257. self.collection.get_active().on_tool_add(dia=float(val))
  3258. else:
  3259. self.inform.emit(
  3260. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3261. else:
  3262. msgbox = QtWidgets.QMessageBox()
  3263. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3264. "Go to Preferences -> General - Show Advanced Options."))
  3265. msgbox.setWindowTitle("Tool adding ...")
  3266. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3267. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3268. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3269. msgbox.exec_()
  3270. # work only if the notebook tab on focus is the Tools_Tab
  3271. if notebook_widget_name == 'tool_tab':
  3272. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3273. tool_add_popup = FCInputDialog(title="New Tool ...",
  3274. text='Enter a Tool Diameter:',
  3275. min=0.0000, max=99.9999, decimals=4)
  3276. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3277. val, ok = tool_add_popup.get_value()
  3278. # and only if the tool is NCC Tool
  3279. if tool_widget == self.ncclear_tool.toolName:
  3280. if ok:
  3281. if float(val) == 0:
  3282. self.inform.emit(
  3283. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3284. return
  3285. self.ncclear_tool.on_tool_add(dia=float(val))
  3286. else:
  3287. self.inform.emit(
  3288. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3289. # and only if the tool is Paint Area Tool
  3290. elif tool_widget == self.paint_tool.toolName:
  3291. if ok:
  3292. if float(val) == 0:
  3293. self.inform.emit(
  3294. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3295. return
  3296. self.paint_tool.on_tool_add(dia=float(val))
  3297. else:
  3298. self.inform.emit(
  3299. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3300. # and only if the tool is Solder Paste Dispensing Tool
  3301. elif tool_widget == self.paste_tool.toolName:
  3302. if ok:
  3303. if float(val) == 0:
  3304. self.inform.emit(
  3305. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3306. return
  3307. self.paste_tool.on_tool_add(dia=float(val))
  3308. else:
  3309. self.inform.emit(
  3310. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3311. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3312. # See description bellow.
  3313. def on_delete_keypress(self):
  3314. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3315. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3316. if notebook_widget_name == 'selected_tab':
  3317. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3318. self.collection.get_active().on_tool_delete()
  3319. # work only if the notebook tab on focus is the Tools_Tab
  3320. elif notebook_widget_name == 'tool_tab':
  3321. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3322. # and only if the tool is NCC Tool
  3323. if tool_widget == self.ncclear_tool.toolName:
  3324. self.ncclear_tool.on_tool_delete()
  3325. # and only if the tool is Paint Tool
  3326. elif tool_widget == self.paint_tool.toolName:
  3327. self.paint_tool.on_tool_delete()
  3328. # and only if the tool is Solder Paste Dispensing Tool
  3329. elif tool_widget == self.paste_tool.toolName:
  3330. self.paste_tool.on_tool_delete()
  3331. else:
  3332. self.on_delete()
  3333. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3334. # some screens you have to be careful where you hover with your mouse.
  3335. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3336. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3337. # Complicated, I know :)
  3338. def on_delete(self):
  3339. """
  3340. Delete the currently selected FlatCAMObjs.
  3341. :return: None
  3342. """
  3343. self.report_usage("on_delete()")
  3344. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3345. # a geometry object before we update it.
  3346. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3347. if self.collection.get_active():
  3348. self.log.debug("on_delete()")
  3349. self.report_usage("on_delete")
  3350. while (self.collection.get_active()):
  3351. self.delete_first_selected()
  3352. self.inform.emit(_("Object(s) deleted ..."))
  3353. # make sure that the selection shape is deleted, too
  3354. self.delete_selection_shape()
  3355. else:
  3356. self.inform.emit(_("Failed. No object(s) selected..."))
  3357. else:
  3358. self.inform.emit(_("Save the work in Editor and try again ..."))
  3359. def on_set_origin(self):
  3360. """
  3361. Set the origin to the left mouse click position
  3362. :return: None
  3363. """
  3364. #display the message for the user
  3365. #and ask him to click on the desired position
  3366. self.report_usage("on_set_origin()")
  3367. self.inform.emit(_('Click to set the origin ...'))
  3368. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3369. def on_jump_to(self):
  3370. """
  3371. Jump to a location by setting the mouse cursor location
  3372. :return:
  3373. """
  3374. self.report_usage("on_jump_to()")
  3375. dia_box = Dialog_box(title=_("Jump to ..."),
  3376. label=_("Enter the coordinates in format X,Y:"),
  3377. icon=QtGui.QIcon('share/jump_to16.png'))
  3378. if dia_box.ok is True:
  3379. try:
  3380. location = eval(dia_box.location)
  3381. if not isinstance(location, tuple):
  3382. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3383. return
  3384. except:
  3385. return
  3386. else:
  3387. return
  3388. self.plotcanvas.fit_center(loc=location)
  3389. cursor = QtGui.QCursor()
  3390. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3391. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3392. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3393. self.inform.emit(_("Done."))
  3394. def on_copy_object(self):
  3395. self.report_usage("on_copy_object()")
  3396. def initialize(obj_init, app):
  3397. obj_init.solid_geometry = obj.solid_geometry
  3398. try:
  3399. if obj.tools:
  3400. obj_init.tools = obj.tools
  3401. except Exception as e:
  3402. log.debug("on_copy_object() --> %s" % str(e))
  3403. def initialize_excellon(obj_init, app):
  3404. obj_init.tools = obj.tools
  3405. # drills are offset, so they need to be deep copied
  3406. obj_init.drills = deepcopy(obj.drills)
  3407. # slots are offset, so they need to be deep copied
  3408. obj_init.slots = deepcopy(obj.slots)
  3409. obj_init.create_geometry()
  3410. for obj in self.collection.get_selected():
  3411. obj_name = obj.options["name"]
  3412. try:
  3413. if isinstance(obj, FlatCAMExcellon):
  3414. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3415. elif isinstance(obj,FlatCAMGerber):
  3416. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3417. elif isinstance(obj,FlatCAMGeometry):
  3418. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3419. except Exception as e:
  3420. return "Operation failed: %s" % str(e)
  3421. def on_copy_object2(self, custom_name):
  3422. def initialize_geometry(obj_init, app):
  3423. obj_init.solid_geometry = obj.solid_geometry
  3424. try:
  3425. if obj.tools:
  3426. obj_init.tools = obj.tools
  3427. except Exception as e:
  3428. log.debug("on_copy_object2() --> %s" % str(e))
  3429. def initialize_gerber(obj_init, app):
  3430. obj_init.solid_geometry = obj.solid_geometry
  3431. obj_init.apertures = deepcopy(obj.apertures)
  3432. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3433. def initialize_excellon(obj_init, app):
  3434. obj_init.tools = obj.tools
  3435. # drills are offset, so they need to be deep copied
  3436. obj_init.drills = deepcopy(obj.drills)
  3437. # slots are offset, so they need to be deep copied
  3438. obj_init.slots = deepcopy(obj.slots)
  3439. obj_init.create_geometry()
  3440. for obj in self.collection.get_selected():
  3441. obj_name = obj.options["name"]
  3442. try:
  3443. if isinstance(obj, FlatCAMExcellon):
  3444. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3445. elif isinstance(obj,FlatCAMGerber):
  3446. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3447. elif isinstance(obj,FlatCAMGeometry):
  3448. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3449. except Exception as e:
  3450. return "Operation failed: %s" % str(e)
  3451. def on_rename_object(self, text):
  3452. self.report_usage("on_rename_object()")
  3453. named_obj = self.collection.get_active()
  3454. for obj in named_obj:
  3455. if obj is list:
  3456. self.on_rename_object(text)
  3457. else:
  3458. try:
  3459. obj.options['name'] = text
  3460. except:
  3461. log.warning("Could not rename the object in the list")
  3462. def on_copy_object_as_geometry(self):
  3463. self.report_usage("on_copy_object_as_geometry()")
  3464. def initialize(obj_init, app):
  3465. obj_init.solid_geometry = obj.solid_geometry
  3466. if obj.tools:
  3467. obj_init.tools = obj.tools
  3468. def initialize_excellon(obj, app):
  3469. objs = self.collection.get_selected()
  3470. FlatCAMGeometry.merge(objs, obj)
  3471. for obj in self.collection.get_selected():
  3472. obj_name = obj.options["name"]
  3473. try:
  3474. if isinstance(obj, FlatCAMExcellon):
  3475. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3476. else:
  3477. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3478. except Exception as e:
  3479. return "Operation failed: %s" % str(e)
  3480. def on_set_zero_click(self, event):
  3481. #this function will be available only for mouse left click
  3482. pos =[]
  3483. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3484. if event.button == 1:
  3485. if self.grid_status() == True:
  3486. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3487. else:
  3488. pos = pos_canvas
  3489. x = 0 - pos[0]
  3490. y = 0 - pos[1]
  3491. for obj in self.collection.get_list():
  3492. obj.offset((x,y))
  3493. self.object_changed.emit(obj)
  3494. obj.plot()
  3495. # Update the object bounding box options
  3496. a, b, c, d = obj.bounds()
  3497. obj.options['xmin'] = a
  3498. obj.options['ymin'] = b
  3499. obj.options['xmax'] = c
  3500. obj.options['ymax'] = d
  3501. # self.plot_all(zoom=False)
  3502. self.inform.emit(_('[success] Origin set ...'))
  3503. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3504. self.should_we_save = True
  3505. def on_selectall(self):
  3506. self.report_usage("on_selectall()")
  3507. # delete the possible selection box around a possible selected object
  3508. self.delete_selection_shape()
  3509. for name in self.collection.get_names():
  3510. self.collection.set_active(name)
  3511. curr_sel_obj = self.collection.get_by_name(name)
  3512. # create the selection box around the selected object
  3513. self.draw_selection_shape(curr_sel_obj)
  3514. def on_preferences(self):
  3515. # add the tab if it was closed
  3516. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3517. # delete the absolute and relative position and messages in the infobar
  3518. self.ui.position_label.setText("")
  3519. self.ui.rel_position_label.setText("")
  3520. # Switch plot_area to preferences page
  3521. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3522. self.ui.show()
  3523. def on_flipy(self):
  3524. self.report_usage("on_flipy()")
  3525. obj_list = self.collection.get_selected()
  3526. xminlist = []
  3527. yminlist = []
  3528. xmaxlist = []
  3529. ymaxlist = []
  3530. if not obj_list:
  3531. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3532. else:
  3533. try:
  3534. # first get a bounding box to fit all
  3535. for obj in obj_list:
  3536. xmin, ymin, xmax, ymax = obj.bounds()
  3537. xminlist.append(xmin)
  3538. yminlist.append(ymin)
  3539. xmaxlist.append(xmax)
  3540. ymaxlist.append(ymax)
  3541. # get the minimum x,y and maximum x,y for all objects selected
  3542. xminimal = min(xminlist)
  3543. yminimal = min(yminlist)
  3544. xmaximal = max(xmaxlist)
  3545. ymaximal = max(ymaxlist)
  3546. px = 0.5 * (xminimal + xmaximal)
  3547. py = 0.5 * (yminimal + ymaximal)
  3548. # execute mirroring
  3549. for obj in obj_list:
  3550. obj.mirror('X', [px, py])
  3551. obj.plot()
  3552. self.object_changed.emit(obj)
  3553. self.inform.emit(_("[success] Flip on Y axis done."))
  3554. except Exception as e:
  3555. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3556. return
  3557. def on_flipx(self):
  3558. self.report_usage("on_flipx()")
  3559. obj_list = self.collection.get_selected()
  3560. xminlist = []
  3561. yminlist = []
  3562. xmaxlist = []
  3563. ymaxlist = []
  3564. if not obj_list:
  3565. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3566. else:
  3567. try:
  3568. # first get a bounding box to fit all
  3569. for obj in obj_list:
  3570. xmin, ymin, xmax, ymax = obj.bounds()
  3571. xminlist.append(xmin)
  3572. yminlist.append(ymin)
  3573. xmaxlist.append(xmax)
  3574. ymaxlist.append(ymax)
  3575. # get the minimum x,y and maximum x,y for all objects selected
  3576. xminimal = min(xminlist)
  3577. yminimal = min(yminlist)
  3578. xmaximal = max(xmaxlist)
  3579. ymaximal = max(ymaxlist)
  3580. px = 0.5 * (xminimal + xmaximal)
  3581. py = 0.5 * (yminimal + ymaximal)
  3582. # execute mirroring
  3583. for obj in obj_list:
  3584. obj.mirror('Y', [px, py])
  3585. obj.plot()
  3586. self.object_changed.emit(obj)
  3587. self.inform.emit(_("[success] Flip on X axis done."))
  3588. except Exception as e:
  3589. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3590. return
  3591. def on_rotate(self, silent=False, preset=None):
  3592. self.report_usage("on_rotate()")
  3593. obj_list = self.collection.get_selected()
  3594. xminlist = []
  3595. yminlist = []
  3596. xmaxlist = []
  3597. ymaxlist = []
  3598. if not obj_list:
  3599. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  3600. else:
  3601. if silent is False:
  3602. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3603. min=-360, max=360, decimals=4,
  3604. init_val=float(self.defaults['tools_transform_rotate']))
  3605. num, ok = rotatebox.get_value()
  3606. else:
  3607. num = preset
  3608. ok = True
  3609. if ok:
  3610. try:
  3611. # first get a bounding box to fit all
  3612. for obj in obj_list:
  3613. xmin, ymin, xmax, ymax = obj.bounds()
  3614. xminlist.append(xmin)
  3615. yminlist.append(ymin)
  3616. xmaxlist.append(xmax)
  3617. ymaxlist.append(ymax)
  3618. # get the minimum x,y and maximum x,y for all objects selected
  3619. xminimal = min(xminlist)
  3620. yminimal = min(yminlist)
  3621. xmaximal = max(xmaxlist)
  3622. ymaximal = max(ymaxlist)
  3623. px = 0.5 * (xminimal + xmaximal)
  3624. py = 0.5 * (yminimal + ymaximal)
  3625. for sel_obj in obj_list:
  3626. sel_obj.rotate(-float(num), point=(px, py))
  3627. sel_obj.plot()
  3628. self.object_changed.emit(sel_obj)
  3629. self.inform.emit(_("[success] Rotation done."))
  3630. except Exception as e:
  3631. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3632. return
  3633. def on_skewx(self):
  3634. self.report_usage("on_skewx()")
  3635. obj_list = self.collection.get_selected()
  3636. xminlist = []
  3637. yminlist = []
  3638. if not obj_list:
  3639. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  3640. else:
  3641. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3642. min=-360, max=360, decimals=4,
  3643. init_val=float(self.defaults['tools_transform_skew_x']))
  3644. num, ok = skewxbox.get_value()
  3645. if ok:
  3646. # first get a bounding box to fit all
  3647. for obj in obj_list:
  3648. xmin, ymin, xmax, ymax = obj.bounds()
  3649. xminlist.append(xmin)
  3650. yminlist.append(ymin)
  3651. # get the minimum x,y and maximum x,y for all objects selected
  3652. xminimal = min(xminlist)
  3653. yminimal = min(yminlist)
  3654. for obj in obj_list:
  3655. obj.skew(num, 0, point=(xminimal, yminimal))
  3656. obj.plot()
  3657. self.object_changed.emit(obj)
  3658. self.inform.emit(_("[success] Skew on X axis done."))
  3659. def on_skewy(self):
  3660. self.report_usage("on_skewy()")
  3661. obj_list = self.collection.get_selected()
  3662. xminlist = []
  3663. yminlist = []
  3664. if not obj_list:
  3665. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  3666. else:
  3667. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3668. min=-360, max=360, decimals=4,
  3669. init_val=float(self.defaults['tools_transform_skew_y']))
  3670. num, ok = skewybox.get_value()
  3671. if ok:
  3672. # first get a bounding box to fit all
  3673. for obj in obj_list:
  3674. xmin, ymin, xmax, ymax = obj.bounds()
  3675. xminlist.append(xmin)
  3676. yminlist.append(ymin)
  3677. # get the minimum x,y and maximum x,y for all objects selected
  3678. xminimal = min(xminlist)
  3679. yminimal = min(yminlist)
  3680. for obj in obj_list:
  3681. obj.skew(0, num, point=(xminimal, yminimal))
  3682. obj.plot()
  3683. self.object_changed.emit(obj)
  3684. self.inform.emit(_("[success] Skew on Y axis done."))
  3685. def delete_first_selected(self):
  3686. # Keep this for later
  3687. try:
  3688. name = self.collection.get_active().options["name"]
  3689. except AttributeError:
  3690. self.log.debug("Nothing selected for deletion")
  3691. return
  3692. # Remove plot
  3693. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3694. # self.plotcanvas.auto_adjust_axes()
  3695. # Clear form
  3696. self.setup_component_editor()
  3697. # Remove from dictionary
  3698. self.collection.delete_active()
  3699. self.inform.emit("Object deleted: %s" % name)
  3700. def on_plots_updated(self):
  3701. """
  3702. Callback used to report when the plots have changed.
  3703. Adjust axes and zooms to fit.
  3704. :return: None
  3705. """
  3706. # self.plotcanvas.auto_adjust_axes()
  3707. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3708. self.on_zoom_fit(None)
  3709. # TODO: Rework toolbar 'clear', 'replot' functions
  3710. def on_toolbar_replot(self):
  3711. """
  3712. Callback for toolbar button. Re-plots all objects.
  3713. :return: None
  3714. """
  3715. self.report_usage("on_toolbar_replot")
  3716. self.log.debug("on_toolbar_replot()")
  3717. try:
  3718. self.collection.get_active().read_form()
  3719. except AttributeError:
  3720. self.log.debug("on_toolbar_replot(): AttributeError")
  3721. pass
  3722. self.plot_all()
  3723. def on_row_activated(self, index):
  3724. if index.isValid():
  3725. if index.internalPointer().parent_item != self.collection.root_item:
  3726. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3727. def grid_status(self):
  3728. if self.ui.grid_snap_btn.isChecked():
  3729. return 1
  3730. else:
  3731. return 0
  3732. def populate_cmenu_grids(self):
  3733. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3734. self.ui.cmenu_gridmenu.clear()
  3735. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3736. for grid in sorted_list:
  3737. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3738. action.triggered.connect(self.set_grid)
  3739. self.ui.cmenu_gridmenu.addSeparator()
  3740. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3741. grid_add.triggered.connect(self.on_grid_add)
  3742. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3743. grid_delete.triggered.connect(self.on_grid_delete)
  3744. def set_grid(self):
  3745. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3746. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3747. def on_grid_add(self):
  3748. ## Current application units in lower Case
  3749. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3750. grid_add_popup = FCInputDialog(title="New Grid ...",
  3751. text='Enter a Grid VAlue:',
  3752. min=0.0000, max=99.9999, decimals=4)
  3753. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3754. val, ok = grid_add_popup.get_value()
  3755. if ok:
  3756. if float(val) == 0:
  3757. self.inform.emit(
  3758. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3759. return
  3760. else:
  3761. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3762. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3763. self.inform.emit(
  3764. _("[success] New Grid added ..."))
  3765. else:
  3766. self.inform.emit(
  3767. _("[WARNING_NOTCL] Grid already exists ..."))
  3768. else:
  3769. self.inform.emit(
  3770. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  3771. def on_grid_delete(self):
  3772. ## Current application units in lower Case
  3773. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3774. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3775. text='Enter a Grid Value:',
  3776. min=0.0000, max=99.9999, decimals=4)
  3777. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3778. val, ok = grid_del_popup.get_value()
  3779. if ok:
  3780. if float(val) == 0:
  3781. self.inform.emit(
  3782. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3783. return
  3784. else:
  3785. try:
  3786. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3787. except ValueError:
  3788. self.inform.emit(
  3789. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  3790. return
  3791. self.inform.emit(
  3792. _("[success] Grid Value deleted ..."))
  3793. else:
  3794. self.inform.emit(
  3795. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  3796. def on_shortcut_list(self):
  3797. self.report_usage("on_shortcut_list()")
  3798. # add the tab if it was closed
  3799. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3800. # delete the absolute and relative position and messages in the infobar
  3801. self.ui.position_label.setText("")
  3802. self.ui.rel_position_label.setText("")
  3803. # Switch plot_area to preferences page
  3804. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3805. self.ui.show()
  3806. def on_select_tab(self, name):
  3807. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3808. if self.ui.splitter.sizes()[0] == 0:
  3809. self.ui.splitter.setSizes([1, 1])
  3810. else:
  3811. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  3812. self.ui.splitter.setSizes([0, 1])
  3813. if name == 'project':
  3814. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3815. elif name == 'selected':
  3816. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3817. elif name == 'tool':
  3818. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3819. def on_copy_name(self):
  3820. self.report_usage("on_copy_name()")
  3821. obj = self.collection.get_active()
  3822. try:
  3823. name = obj.options["name"]
  3824. except AttributeError:
  3825. log.debug("on_copy_name() --> No object selected to copy it's name")
  3826. self.inform.emit(_("[WARNING_NOTCL]No object selected to copy it's name"))
  3827. return
  3828. self.clipboard.setText(name)
  3829. self.inform.emit(_("Name copied on clipboard ..."))
  3830. def on_mouse_click_over_plot(self, event):
  3831. """
  3832. Default actions are:
  3833. :param event: Contains information about the event, like which button
  3834. was clicked, the pixel coordinates and the axes coordinates.
  3835. :return: None
  3836. """
  3837. self.pos = []
  3838. # So it can receive key presses
  3839. self.plotcanvas.vispy_canvas.native.setFocus()
  3840. # Set the mouse button for panning
  3841. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3842. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3843. if self.grid_status() == True:
  3844. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3845. self.app_cursor.enabled = True
  3846. else:
  3847. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3848. self.app_cursor.enabled = False
  3849. try:
  3850. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3851. if event.button == 1:
  3852. # Reset here the relative coordinates so there is a new reference on the click position
  3853. if self.rel_point1 is None:
  3854. self.rel_point1 = self.pos
  3855. else:
  3856. self.rel_point2 = copy(self.rel_point1)
  3857. self.rel_point1 = self.pos
  3858. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3859. if modifiers == QtCore.Qt.ShiftModifier:
  3860. # do not auto open the Project Tab
  3861. self.click_noproject = True
  3862. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3863. return
  3864. self.on_mouse_move_over_plot(event, origin_click=True)
  3865. except Exception as e:
  3866. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3867. def on_double_click_over_plot(self, event):
  3868. self.doubleclick = True
  3869. def on_mouse_move_over_plot(self, event, origin_click=None):
  3870. """
  3871. Callback for the mouse motion event over the plot. This event is generated
  3872. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3873. For details, see: http://matplotlib.org/users/event_handling.html
  3874. :param event: Contains information about the event.
  3875. :param origin_click
  3876. :return: None
  3877. """
  3878. # So it can receive key presses
  3879. self.plotcanvas.vispy_canvas.native.setFocus()
  3880. self.pos_jump = event.pos
  3881. if origin_click is True:
  3882. pass
  3883. else:
  3884. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3885. if event.button == 2:
  3886. self.panning_action = True
  3887. return
  3888. else:
  3889. self.panning_action = False
  3890. if self.rel_point1 is not None:
  3891. try: # May fail in case mouse not within axes
  3892. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3893. if self.grid_status():
  3894. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3895. self.app_cursor.enabled = True
  3896. # Update cursor
  3897. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3898. else:
  3899. pos = (pos_canvas[0], pos_canvas[1])
  3900. self.app_cursor.enabled = False
  3901. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3902. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3903. dx = pos[0] - self.rel_point1[0]
  3904. dy = pos[1] - self.rel_point1[1]
  3905. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3906. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3907. self.mouse = [pos[0], pos[1]]
  3908. # if the mouse is moved and the LMB is clicked then the action is a selection
  3909. if event.is_dragging == 1 and event.button == 1:
  3910. self.delete_selection_shape()
  3911. if dx < 0:
  3912. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3913. face_color=self.defaults['global_alt_sel_fill'])
  3914. self.selection_type = False
  3915. else:
  3916. self.draw_moving_selection_shape(self.pos, pos)
  3917. self.selection_type = True
  3918. # hover effect - enabled in Preferences -> General -> GUI Settings
  3919. if self.defaults['global_hover']:
  3920. for obj in self.collection.get_list():
  3921. try:
  3922. # select the object(s) only if it is enabled (plotted)
  3923. if obj.options['plot']:
  3924. if obj not in self.collection.get_selected():
  3925. poly_obj = Polygon(
  3926. [(obj.options['xmin'], obj.options['ymin']),
  3927. (obj.options['xmax'], obj.options['ymin']),
  3928. (obj.options['xmax'], obj.options['ymax']),
  3929. (obj.options['xmin'], obj.options['ymax'])]
  3930. )
  3931. if Point(pos).within(poly_obj):
  3932. if obj.isHovering is False:
  3933. obj.isHovering = True
  3934. obj.notHovering = True
  3935. # create the selection box around the selected object
  3936. self.draw_hover_shape(obj, color='#d1e0e0')
  3937. else:
  3938. if obj.notHovering is True:
  3939. obj.notHovering = False
  3940. obj.isHovering = False
  3941. self.delete_hover_shape()
  3942. except:
  3943. # the Exception here will happen if we try to select on screen and we have an
  3944. # newly (and empty) just created Geometry or Excellon object that do not have the
  3945. # xmin, xmax, ymin, ymax options.
  3946. # In this case poly_obj creation (see above) will fail
  3947. pass
  3948. except:
  3949. self.ui.position_label.setText("")
  3950. self.ui.rel_position_label.setText("")
  3951. self.mouse = None
  3952. def on_mouse_click_release_over_plot(self, event):
  3953. """
  3954. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3955. and has been registered in ''self.__init__()''.
  3956. :param event: contains information about the event.
  3957. :return:
  3958. """
  3959. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3960. if self.grid_status():
  3961. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3962. else:
  3963. pos = (pos_canvas[0], pos_canvas[1])
  3964. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3965. # canvas menu
  3966. try:
  3967. if event.button == 2: # right click
  3968. if self.panning_action is True:
  3969. self.panning_action = False
  3970. else:
  3971. self.cursor = QtGui.QCursor()
  3972. self.populate_cmenu_grids()
  3973. self.ui.popMenu.popup(self.cursor.pos())
  3974. except Exception as e:
  3975. log.warning("Error: %s" % str(e))
  3976. return
  3977. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3978. # selection and then select a type of selection ("enclosing" or "touching")
  3979. try:
  3980. if event.button == 1: # left click
  3981. if self.doubleclick is True:
  3982. self.doubleclick = False
  3983. if self.collection.get_selected():
  3984. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3985. if self.ui.splitter.sizes()[0] == 0:
  3986. self.ui.splitter.setSizes([1, 1])
  3987. # delete the selection shape(S) as it may be in the way
  3988. self.delete_selection_shape()
  3989. self.delete_hover_shape()
  3990. else:
  3991. if self.selection_type is not None:
  3992. self.selection_area_handler(self.pos, pos, self.selection_type)
  3993. self.selection_type = None
  3994. else:
  3995. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3996. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3997. # and if it's not selected then it will be selected
  3998. if modifiers == QtCore.Qt.ControlModifier:
  3999. # If there is no active command (self.command_active is None) then we check if we clicked on
  4000. # a object by checking the bounding limits against mouse click position
  4001. if self.command_active is None:
  4002. self.select_objects(key='CTRL')
  4003. self.delete_hover_shape()
  4004. else:
  4005. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4006. # checking the bounding limits against mouse click position
  4007. if self.command_active is None:
  4008. self.select_objects()
  4009. self.delete_hover_shape()
  4010. except Exception as e:
  4011. log.warning("Error: %s" % str(e))
  4012. return
  4013. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4014. """
  4015. :param start_pos: mouse position when the selection LMB click was done
  4016. :param end_pos: mouse position when the left mouse button is released
  4017. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4018. :return:
  4019. """
  4020. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4021. self.delete_selection_shape()
  4022. for obj in self.collection.get_list():
  4023. try:
  4024. # select the object(s) only if it is enabled (plotted)
  4025. if obj.options['plot']:
  4026. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4027. (obj.options['xmax'], obj.options['ymin']),
  4028. (obj.options['xmax'], obj.options['ymax']),
  4029. (obj.options['xmin'], obj.options['ymax'])])
  4030. if sel_type is True:
  4031. if poly_obj.within(poly_selection):
  4032. # create the selection box around the selected object
  4033. self.draw_selection_shape(obj)
  4034. self.collection.set_active(obj.options['name'])
  4035. else:
  4036. if poly_selection.intersects(poly_obj):
  4037. # create the selection box around the selected object
  4038. self.draw_selection_shape(obj)
  4039. self.collection.set_active(obj.options['name'])
  4040. except:
  4041. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4042. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4043. # In this case poly_obj creation (see above) will fail
  4044. pass
  4045. def select_objects(self, key=None):
  4046. # list where we store the overlapped objects under our mouse left click position
  4047. objects_under_the_click_list = []
  4048. # Populate the list with the overlapped objects on the click position
  4049. curr_x, curr_y = self.pos
  4050. for obj in self.all_objects_list:
  4051. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4052. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4053. if obj.options['name'] not in objects_under_the_click_list:
  4054. if obj.options['plot']:
  4055. # add objects to the objects_under_the_click list only if the object is plotted
  4056. # (active and not disabled)
  4057. objects_under_the_click_list.append(obj.options['name'])
  4058. try:
  4059. # If there is no element in the overlapped objects list then make everyone inactive
  4060. # because we selected "nothing"
  4061. if not objects_under_the_click_list:
  4062. self.collection.set_all_inactive()
  4063. # delete the possible selection box around a possible selected object
  4064. self.delete_selection_shape()
  4065. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4066. # only when working on App
  4067. if self.call_source == 'app':
  4068. if self.click_noproject is False:
  4069. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4070. else:
  4071. # restore auto open the Project Tab
  4072. self.click_noproject = False
  4073. # delete any text in the status bar, implicitly the last object name that was selected
  4074. self.inform.emit("")
  4075. else:
  4076. self.call_source = 'app'
  4077. else:
  4078. # case when there is only an object under the click and we toggle it
  4079. if len(objects_under_the_click_list) == 1:
  4080. if self.collection.get_active() is None :
  4081. self.collection.set_active(objects_under_the_click_list[0])
  4082. # create the selection box around the selected object
  4083. curr_sel_obj = self.collection.get_active()
  4084. self.draw_selection_shape(curr_sel_obj)
  4085. # self.inform.emit('[selected] %s: %s selected' %
  4086. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4087. if curr_sel_obj.kind == 'gerber':
  4088. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4089. ('green', str(curr_sel_obj.options['name'])))
  4090. elif curr_sel_obj.kind == 'excellon':
  4091. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4092. ('brown', str(curr_sel_obj.options['name'])))
  4093. elif curr_sel_obj.kind == 'cncjob':
  4094. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4095. ('blue', str(curr_sel_obj.options['name'])))
  4096. elif curr_sel_obj.kind == 'geometry':
  4097. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4098. ('red', str(curr_sel_obj.options['name'])))
  4099. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4100. self.collection.set_all_inactive()
  4101. self.delete_selection_shape()
  4102. self.collection.set_active(objects_under_the_click_list[0])
  4103. # create the selection box around the selected object
  4104. curr_sel_obj = self.collection.get_active()
  4105. self.draw_selection_shape(curr_sel_obj)
  4106. # self.inform.emit('[selected] %s: %s selected' %
  4107. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4108. if curr_sel_obj.kind == 'gerber':
  4109. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4110. ('green', str(curr_sel_obj.options['name'])))
  4111. elif curr_sel_obj.kind == 'excellon':
  4112. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4113. ('brown', str(curr_sel_obj.options['name'])))
  4114. elif curr_sel_obj.kind == 'cncjob':
  4115. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4116. ('blue', str(curr_sel_obj.options['name'])))
  4117. elif curr_sel_obj.kind == 'geometry':
  4118. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4119. ('red', str(curr_sel_obj.options['name'])))
  4120. else:
  4121. self.collection.set_all_inactive()
  4122. self.delete_selection_shape()
  4123. if self.call_source == 'app':
  4124. # delete any text in the status bar, implicitly the last object name that was selected
  4125. self.inform.emit("")
  4126. else:
  4127. self.call_source = 'app'
  4128. else:
  4129. # If there is no selected object
  4130. # make active the first element of the overlapped objects list
  4131. if self.collection.get_active() is None:
  4132. self.collection.set_active(objects_under_the_click_list[0])
  4133. name_sel_obj = self.collection.get_active().options['name']
  4134. # In case that there is a selected object but it is not in the overlapped object list
  4135. # make that object inactive and activate the first element in the overlapped object list
  4136. if name_sel_obj not in objects_under_the_click_list:
  4137. self.collection.set_inactive(name_sel_obj)
  4138. name_sel_obj = objects_under_the_click_list[0]
  4139. self.collection.set_active(name_sel_obj)
  4140. else:
  4141. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4142. self.collection.set_all_inactive()
  4143. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4144. len(objects_under_the_click_list)])
  4145. curr_sel_obj = self.collection.get_active()
  4146. # delete the possible selection box around a possible selected object
  4147. self.delete_selection_shape()
  4148. # create the selection box around the selected object
  4149. self.draw_selection_shape(curr_sel_obj)
  4150. # self.inform.emit('[selected] %s: %s selected' %
  4151. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4152. if curr_sel_obj.kind == 'gerber':
  4153. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4154. ('green', str(curr_sel_obj.options['name'])))
  4155. elif curr_sel_obj.kind == 'excellon':
  4156. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4157. ('brown', str(curr_sel_obj.options['name'])))
  4158. elif curr_sel_obj.kind == 'cncjob':
  4159. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4160. ('blue', str(curr_sel_obj.options['name'])))
  4161. elif curr_sel_obj.kind == 'geometry':
  4162. self.inform.emit(_('[selected]<span style="color:%s;">%s</span> selected') %
  4163. ('red', str(curr_sel_obj.options['name'])))
  4164. # for obj in self.collection.get_list():
  4165. # obj.plot()
  4166. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4167. # TODO: on selected objects change the object colors and do not draw the selection box
  4168. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4169. except Exception as e:
  4170. log.error("[ERROR] Something went bad. %s" % str(e))
  4171. return
  4172. def delete_hover_shape(self):
  4173. self.hover_shapes.clear()
  4174. self.hover_shapes.redraw()
  4175. def draw_hover_shape(self, sel_obj, color=None):
  4176. """
  4177. :param sel_obj: the object for which the hover shape must be drawn
  4178. :return:
  4179. """
  4180. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4181. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4182. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4183. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4184. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4185. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4186. hover_rect = hover_rect.buffer(-0.1)
  4187. hover_rect = hover_rect.buffer(0.2)
  4188. else:
  4189. hover_rect = hover_rect.buffer(-0.00393)
  4190. hover_rect = hover_rect.buffer(0.00787)
  4191. if color:
  4192. face = Color(color)
  4193. face.alpha = 0.2
  4194. outline = Color(color, alpha=0.8)
  4195. else:
  4196. face = Color(self.defaults['global_sel_fill'])
  4197. face.alpha = 0.2
  4198. outline = self.defaults['global_sel_line']
  4199. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4200. def delete_selection_shape(self):
  4201. self.move_tool.sel_shapes.clear()
  4202. self.move_tool.sel_shapes.redraw()
  4203. def draw_selection_shape(self, sel_obj, color=None):
  4204. """
  4205. :param sel_obj: the object for which the selection shape must be drawn
  4206. :return:
  4207. """
  4208. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4209. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4210. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4211. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4212. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4213. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4214. sel_rect = sel_rect.buffer(-0.1)
  4215. sel_rect = sel_rect.buffer(0.2)
  4216. else:
  4217. sel_rect = sel_rect.buffer(-0.00393)
  4218. sel_rect = sel_rect.buffer(0.00787)
  4219. if color:
  4220. face = Color(color, alpha=0.2)
  4221. outline = Color(color, alpha=0.8)
  4222. else:
  4223. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4224. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4225. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4226. face_color=face, update=True, layer=0, tolerance=None))
  4227. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4228. """
  4229. :param old_coords: old coordinates
  4230. :param coords: new coordinates
  4231. :return:
  4232. """
  4233. if 'color' in kwargs:
  4234. color = kwargs['color']
  4235. else:
  4236. color = self.defaults['global_sel_line']
  4237. if 'face_color' in kwargs:
  4238. face_color = kwargs['face_color']
  4239. else:
  4240. face_color = self.defaults['global_sel_fill']
  4241. x0, y0 = old_coords
  4242. x1, y1 = coords
  4243. pt1 = (x0, y0)
  4244. pt2 = (x1, y0)
  4245. pt3 = (x1, y1)
  4246. pt4 = (x0, y1)
  4247. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4248. color_t = Color(face_color)
  4249. color_t.alpha = 0.3
  4250. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4251. layer=0, tolerance=None)
  4252. def on_file_new_click(self):
  4253. if self.collection.get_list() and self.should_we_save:
  4254. msgbox = QtWidgets.QMessageBox()
  4255. # msgbox.setText("<B>Save changes ...</B>")
  4256. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4257. "Creating a New project will delete them.\n"
  4258. "Do you want to Save the project?"))
  4259. msgbox.setWindowTitle(_("Save changes"))
  4260. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4261. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4262. QtWidgets.QMessageBox.No)
  4263. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4264. response = msgbox.exec_()
  4265. if response == QtWidgets.QMessageBox.Yes:
  4266. self.on_file_saveprojectas()
  4267. elif response == QtWidgets.QMessageBox.Cancel:
  4268. return
  4269. self.on_file_new()
  4270. else:
  4271. self.on_file_new()
  4272. self.inform.emit(_("[success] New Project created..."))
  4273. def on_file_new(self):
  4274. """
  4275. Callback for menu item File->New. Returns the application to its
  4276. startup state. This method is thread-safe.
  4277. :return: None
  4278. """
  4279. self.report_usage("on_file_new")
  4280. # Remove everything from memory
  4281. App.log.debug("on_file_new()")
  4282. # Clear pool
  4283. self.clear_pool()
  4284. #delete shapes left drawn from mark shape_collections, if any
  4285. for obj in self.collection.get_list():
  4286. try:
  4287. obj.mark_shapes.enabled = False
  4288. obj.mark_shapes.clear(update=True)
  4289. except:
  4290. pass
  4291. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4292. self.init_tcl()
  4293. self.delete_selection_shape()
  4294. self.collection.delete_all()
  4295. self.setup_component_editor()
  4296. # Clear project filename
  4297. self.project_filename = None
  4298. # Load the application defaults
  4299. self.load_defaults(filename='current_defaults')
  4300. # Re-fresh project options
  4301. self.on_options_app2project()
  4302. # Init Tools
  4303. self.init_tools()
  4304. # Close any Tabs opened in the Plot Tab Area section
  4305. for index in range(self.ui.plot_tab_area.count()):
  4306. self.ui.plot_tab_area.closeTab(index)
  4307. # for whatever reason previous command does not close the last tab so I do it manually
  4308. self.ui.plot_tab_area.closeTab(0)
  4309. # # And then add again the Plot Area
  4310. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4311. self.ui.plot_tab_area.protectTab(0)
  4312. # take the focus of the Notebook on Project Tab.
  4313. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4314. def obj_properties(self):
  4315. self.report_usage("obj_properties()")
  4316. self.properties_tool.run(toggle=False)
  4317. def on_project_context_save(self):
  4318. obj = self.collection.get_active()
  4319. if type(obj) == FlatCAMGeometry:
  4320. self.on_file_exportdxf()
  4321. elif type(obj) == FlatCAMExcellon:
  4322. self.on_file_saveexcellon()
  4323. elif type(obj) == FlatCAMCNCjob:
  4324. obj.on_exportgcode_button_click()
  4325. elif type(obj) == FlatCAMGerber:
  4326. self.on_file_savegerber()
  4327. def on_view_source(self):
  4328. try:
  4329. obj = self.collection.get_active()
  4330. except:
  4331. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  4332. return 'fail'
  4333. # then append the text from GCode to the text editor
  4334. try:
  4335. file = StringIO(obj.source_file)
  4336. except AttributeError:
  4337. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  4338. return 'fail'
  4339. # add the tab if it was closed
  4340. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  4341. # first clear previous text in text editor (if any)
  4342. self.ui.code_editor.clear()
  4343. # Switch plot_area to CNCJob tab
  4344. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  4345. try:
  4346. for line in file:
  4347. proc_line = str(line).strip('\n')
  4348. self.ui.code_editor.append(proc_line)
  4349. except Exception as e:
  4350. log.debug('App.on_view_source() -->%s' % str(e))
  4351. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  4352. return
  4353. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4354. self.handleTextChanged()
  4355. self.ui.show()
  4356. # if type(obj) == FlatCAMGerber:
  4357. # self.on_file_exportdxf()
  4358. # elif type(obj) == FlatCAMExcellon:
  4359. # self.on_file_exportexcellon()
  4360. def obj_move(self):
  4361. self.report_usage("obj_move()")
  4362. self.move_tool.run()
  4363. def on_fileopengerber(self):
  4364. """
  4365. File menu callback for opening a Gerber.
  4366. :return: None
  4367. """
  4368. self.report_usage("on_fileopengerber")
  4369. App.log.debug("on_fileopengerber()")
  4370. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4371. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4372. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4373. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4374. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4375. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4376. "Allegro Files (*.art);;" \
  4377. "Mentor Files (*.pho *.gdo);;" \
  4378. "All Files (*.*)"
  4379. try:
  4380. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4381. directory=self.get_last_folder(), filter=_filter_)
  4382. except TypeError:
  4383. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4384. filenames = [str(filename) for filename in filenames]
  4385. if len(filenames) == 0:
  4386. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4387. else:
  4388. for filename in filenames:
  4389. if filename != '':
  4390. self.worker_task.emit({'fcn': self.open_gerber,
  4391. 'params': [filename]})
  4392. def on_fileopenexcellon(self):
  4393. """
  4394. File menu callback for opening an Excellon file.
  4395. :return: None
  4396. """
  4397. self.report_usage("on_fileopenexcellon")
  4398. App.log.debug("on_fileopenexcellon()")
  4399. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4400. "All Files (*.*)"
  4401. try:
  4402. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4403. directory=self.get_last_folder(), filter=_filter_)
  4404. except TypeError:
  4405. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4406. filenames = [str(filename) for filename in filenames]
  4407. if len(filenames) == 0:
  4408. self.inform.emit(_("[WARNING_NOTCL]Open Excellon cancelled."))
  4409. else:
  4410. for filename in filenames:
  4411. if filename != '':
  4412. self.worker_task.emit({'fcn': self.open_excellon,
  4413. 'params': [filename]})
  4414. def on_fileopengcode(self):
  4415. """
  4416. File menu call back for opening gcode.
  4417. :return: None
  4418. """
  4419. self.report_usage("on_fileopengcode")
  4420. App.log.debug("on_fileopengcode()")
  4421. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4422. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4423. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4424. "All Files (*.*)"
  4425. try:
  4426. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4427. directory=self.get_last_folder(), filter=_filter_)
  4428. except TypeError:
  4429. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4430. filenames = [str(filename) for filename in filenames]
  4431. if len(filenames) == 0:
  4432. self.inform.emit(_("[WARNING_NOTCL]Open G-Code cancelled."))
  4433. else:
  4434. for filename in filenames:
  4435. if filename != '':
  4436. self.worker_task.emit({'fcn': self.open_gcode,
  4437. 'params': [filename]})
  4438. def on_file_openproject(self):
  4439. """
  4440. File menu callback for opening a project.
  4441. :return: None
  4442. """
  4443. self.report_usage("on_file_openproject")
  4444. App.log.debug("on_file_openproject()")
  4445. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4446. try:
  4447. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4448. directory=self.get_last_folder(), filter=_filter_)
  4449. except TypeError:
  4450. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4451. # The Qt methods above will return a QString which can cause problems later.
  4452. # So far json.dump() will fail to serialize it.
  4453. # TODO: Improve the serialization methods and remove this fix.
  4454. filename = str(filename)
  4455. if filename == "":
  4456. self.inform.emit(_("[WARNING_NOTCL]Open Project cancelled."))
  4457. else:
  4458. # self.worker_task.emit({'fcn': self.open_project,
  4459. # 'params': [filename]})
  4460. # The above was failing because open_project() is not
  4461. # thread safe. The new_project()
  4462. self.open_project(filename)
  4463. def on_file_openconfig(self):
  4464. """
  4465. File menu callback for opening a config file.
  4466. :return: None
  4467. """
  4468. self.report_usage("on_file_openconfig")
  4469. App.log.debug("on_file_openconfig()")
  4470. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4471. try:
  4472. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4473. directory=self.data_path, filter=_filter_)
  4474. except TypeError:
  4475. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4476. filter = _filter_)
  4477. if filename == "":
  4478. self.inform.emit(_("[WARNING_NOTCL]Open Config cancelled."))
  4479. else:
  4480. self.open_config_file(filename)
  4481. def on_file_exportsvg(self):
  4482. """
  4483. Callback for menu item File->Export SVG.
  4484. :return: None
  4485. """
  4486. self.report_usage("on_file_exportsvg")
  4487. App.log.debug("on_file_exportsvg()")
  4488. obj = self.collection.get_active()
  4489. if obj is None:
  4490. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4491. msg = _("Please Select a Geometry object to export")
  4492. msgbox = QtWidgets.QMessageBox()
  4493. msgbox.setInformativeText(msg)
  4494. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4495. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4496. msgbox.exec_()
  4497. return
  4498. # Check for more compatible types and add as required
  4499. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4500. and not isinstance(obj, FlatCAMExcellon)):
  4501. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4502. msgbox = QtWidgets.QMessageBox()
  4503. msgbox.setInformativeText(msg)
  4504. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4505. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4506. msgbox.exec_()
  4507. return
  4508. name = self.collection.get_active().options["name"]
  4509. filter = "SVG File (*.svg);;All Files (*.*)"
  4510. try:
  4511. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4512. caption=_("Export SVG"),
  4513. directory=self.get_last_save_folder() + '/' + str(name),
  4514. filter=filter)
  4515. except TypeError:
  4516. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4517. filename = str(filename)
  4518. if filename == "":
  4519. self.inform.emit(_("[WARNING_NOTCL]Export SVG cancelled."))
  4520. return
  4521. else:
  4522. self.export_svg(name, filename)
  4523. self.file_saved.emit("SVG", filename)
  4524. def on_file_exportpng(self):
  4525. self.report_usage("on_file_exportpng")
  4526. App.log.debug("on_file_exportpng()")
  4527. image = _screenshot()
  4528. data = np.asarray(image)
  4529. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4530. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4531. return
  4532. filter_ = "PNG File (*.png);;All Files (*.*)"
  4533. try:
  4534. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4535. caption=_("Export PNG Image"),
  4536. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4537. filter=filter_)
  4538. except TypeError:
  4539. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4540. filename = str(filename)
  4541. if filename == "":
  4542. self.inform.emit(_("Export PNG cancelled."))
  4543. return
  4544. else:
  4545. write_png(filename, data)
  4546. self.file_saved.emit("png", filename)
  4547. def on_file_savegerber(self):
  4548. """
  4549. Callback for menu item File->Export Gerber.
  4550. :return: None
  4551. """
  4552. self.report_usage("on_file_savegerber")
  4553. App.log.debug("on_file_savegerber()")
  4554. obj = self.collection.get_active()
  4555. if obj is None:
  4556. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4557. return
  4558. # Check for more compatible types and add as required
  4559. if not isinstance(obj, FlatCAMGerber):
  4560. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4561. return
  4562. name = self.collection.get_active().options["name"]
  4563. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4564. try:
  4565. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4566. caption="Save Gerber source file",
  4567. directory=self.get_last_save_folder() + '/' + name,
  4568. filter=filter)
  4569. except TypeError:
  4570. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4571. filename = str(filename)
  4572. if filename == "":
  4573. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4574. return
  4575. else:
  4576. self.save_source_file(name, filename)
  4577. self.file_saved.emit("Gerber", filename)
  4578. def on_file_saveexcellon(self):
  4579. """
  4580. Callback for menu item File->Export Gerber.
  4581. :return: None
  4582. """
  4583. self.report_usage("on_file_saveexcellon")
  4584. App.log.debug("on_file_saveexcellon()")
  4585. obj = self.collection.get_active()
  4586. if obj is None:
  4587. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4588. return
  4589. # Check for more compatible types and add as required
  4590. if not isinstance(obj, FlatCAMExcellon):
  4591. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4592. return
  4593. name = self.collection.get_active().options["name"]
  4594. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4595. try:
  4596. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4597. caption=_("Save Excellon source file"),
  4598. directory=self.get_last_save_folder() + '/' + name,
  4599. filter=filter)
  4600. except TypeError:
  4601. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4602. filename = str(filename)
  4603. if filename == "":
  4604. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4605. return
  4606. else:
  4607. self.save_source_file(name, filename)
  4608. self.file_saved.emit("Excellon", filename)
  4609. def on_file_exportexcellon(self):
  4610. """
  4611. Callback for menu item File->Export SVG.
  4612. :return: None
  4613. """
  4614. self.report_usage("on_file_exportexcellon")
  4615. App.log.debug("on_file_exportexcellon()")
  4616. obj = self.collection.get_active()
  4617. if obj is None:
  4618. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  4619. return
  4620. # Check for more compatible types and add as required
  4621. if not isinstance(obj, FlatCAMExcellon):
  4622. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4623. return
  4624. name = self.collection.get_active().options["name"]
  4625. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4626. try:
  4627. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4628. caption=_("Export Excellon"),
  4629. directory=self.get_last_save_folder() + '/' + name,
  4630. filter=filter)
  4631. except TypeError:
  4632. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  4633. filename = str(filename)
  4634. if filename == "":
  4635. self.inform.emit(_("[WARNING_NOTCL]Export Excellon cancelled."))
  4636. return
  4637. else:
  4638. self.export_excellon(name, filename)
  4639. self.file_saved.emit("Excellon", filename)
  4640. def on_file_exportdxf(self):
  4641. """
  4642. Callback for menu item File->Export DXF.
  4643. :return: None
  4644. """
  4645. self.report_usage("on_file_exportdxf")
  4646. App.log.debug("on_file_exportdxf()")
  4647. obj = self.collection.get_active()
  4648. if obj is None:
  4649. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4650. msg = _("Please Select a Geometry object to export")
  4651. msgbox = QtWidgets.QMessageBox()
  4652. msgbox.setInformativeText(msg)
  4653. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4654. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4655. msgbox.exec_()
  4656. return
  4657. # Check for more compatible types and add as required
  4658. if not isinstance(obj, FlatCAMGeometry):
  4659. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  4660. msgbox = QtWidgets.QMessageBox()
  4661. msgbox.setInformativeText(msg)
  4662. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4663. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4664. msgbox.exec_()
  4665. return
  4666. name = self.collection.get_active().options["name"]
  4667. filter = "DXF File (*.DXF);;All Files (*.*)"
  4668. try:
  4669. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4670. caption=_("Export DXF"),
  4671. directory=self.get_last_save_folder() + '/' + name,
  4672. filter=filter)
  4673. except TypeError:
  4674. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  4675. filename = str(filename)
  4676. if filename == "":
  4677. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  4678. return
  4679. else:
  4680. self.export_dxf(name, filename)
  4681. self.file_saved.emit("DXF", filename)
  4682. def on_file_importsvg(self, type_of_obj):
  4683. """
  4684. Callback for menu item File->Import SVG.
  4685. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4686. :type type_of_obj: str
  4687. :return: None
  4688. """
  4689. self.report_usage("on_file_importsvg")
  4690. App.log.debug("on_file_importsvg()")
  4691. filter = "SVG File (*.svg);;All Files (*.*)"
  4692. try:
  4693. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  4694. directory=self.get_last_folder(), filter=filter)
  4695. except TypeError:
  4696. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  4697. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4698. type_of_obj = "geometry"
  4699. filenames = [str(filename) for filename in filenames]
  4700. if len(filenames) == 0:
  4701. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  4702. else:
  4703. for filename in filenames:
  4704. if filename != '':
  4705. self.worker_task.emit({'fcn': self.import_svg,
  4706. 'params': [filename, type_of_obj]})
  4707. def on_file_importdxf(self, type_of_obj):
  4708. """
  4709. Callback for menu item File->Import DXF.
  4710. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4711. :type type_of_obj: str
  4712. :return: None
  4713. """
  4714. self.report_usage("on_file_importdxf")
  4715. App.log.debug("on_file_importdxf()")
  4716. filter = "DXF File (*.DXF);;All Files (*.*)"
  4717. try:
  4718. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  4719. directory=self.get_last_folder(), filter=filter)
  4720. except TypeError:
  4721. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  4722. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4723. type_of_obj = "geometry"
  4724. filenames = [str(filename) for filename in filenames]
  4725. if len(filenames) == 0:
  4726. self.inform.emit(_("[WARNING_NOTCL]Open DXF cancelled."))
  4727. else:
  4728. for filename in filenames:
  4729. if filename != '':
  4730. self.worker_task.emit({'fcn': self.import_dxf,
  4731. 'params': [filename, type_of_obj]})
  4732. def on_filerunscript(self):
  4733. """
  4734. File menu callback for loading and running a TCL script.
  4735. :return: None
  4736. """
  4737. self.report_usage("on_filerunscript")
  4738. App.log.debug("on_file_runscript()")
  4739. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4740. try:
  4741. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  4742. directory=self.get_last_folder(), filter=_filter_)
  4743. except TypeError:
  4744. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  4745. # The Qt methods above will return a QString which can cause problems later.
  4746. # So far json.dump() will fail to serialize it.
  4747. # TODO: Improve the serialization methods and remove this fix.
  4748. filename = str(filename)
  4749. if filename == "":
  4750. self.inform.emit(_("[WARNING_NOTCL]Open TCL script cancelled."))
  4751. else:
  4752. try:
  4753. with open(filename, "r") as tcl_script:
  4754. cmd_line_shellfile_content = tcl_script.read()
  4755. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4756. except Exception as ext:
  4757. print("ERROR: ", ext)
  4758. sys.exit(2)
  4759. def on_file_saveproject(self):
  4760. """
  4761. Callback for menu item File->Save Project. Saves the project to
  4762. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4763. if set to None. The project is saved by calling ``self.save_project()``.
  4764. :return: None
  4765. """
  4766. self.report_usage("on_file_saveproject")
  4767. if self.project_filename is None:
  4768. self.on_file_saveprojectas()
  4769. else:
  4770. self.worker_task.emit({'fcn': self.save_project,
  4771. 'params': [self.project_filename]})
  4772. # self.save_project(self.project_filename)
  4773. self.file_opened.emit("project", self.project_filename)
  4774. self.file_saved.emit("project", self.project_filename)
  4775. self.should_we_save = False
  4776. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4777. """
  4778. Callback for menu item File->Save Project As... Opens a file
  4779. chooser and saves the project to the given file via
  4780. ``self.save_project()``.
  4781. :return: None
  4782. """
  4783. self.report_usage("on_file_saveprojectas")
  4784. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4785. try:
  4786. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4787. caption=_("Save Project As ..."),
  4788. directory=_('%s/Project_%s') % (str(self.get_last_save_folder()), str(self.date.replace('-', ''))),
  4789. filter=filter_)
  4790. except TypeError:
  4791. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  4792. filename = str(filename)
  4793. if filename == '':
  4794. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  4795. return
  4796. try:
  4797. f = open(filename, 'r')
  4798. f.close()
  4799. exists = True
  4800. except IOError:
  4801. exists = False
  4802. if thread is True:
  4803. self.worker_task.emit({'fcn': self.save_project,
  4804. 'params': [filename]})
  4805. else:
  4806. self.save_project(filename)
  4807. # self.save_project(filename)
  4808. self.file_opened.emit("project", filename)
  4809. self.file_saved.emit("project", filename)
  4810. if not make_copy:
  4811. self.project_filename = filename
  4812. self.should_we_save = False
  4813. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4814. """
  4815. Exports a Geometry Object to an SVG file.
  4816. :param filename: Path to the SVG file to save to.
  4817. :return:
  4818. """
  4819. self.report_usage("export_svg()")
  4820. if filename is None:
  4821. filename = self.defaults["global_last_save_folder"]
  4822. self.log.debug("export_svg()")
  4823. try:
  4824. obj = self.collection.get_by_name(str(obj_name))
  4825. except:
  4826. # TODO: The return behavior has not been established... should raise exception?
  4827. return "Could not retrieve object: %s" % obj_name
  4828. with self.proc_container.new(_("Exporting SVG")) as proc:
  4829. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4830. # Determine bounding area for svg export
  4831. bounds = obj.bounds()
  4832. size = obj.size()
  4833. # Convert everything to strings for use in the xml doc
  4834. svgwidth = str(size[0])
  4835. svgheight = str(size[1])
  4836. minx = str(bounds[0])
  4837. miny = str(bounds[1] - size[1])
  4838. uom = obj.units.lower()
  4839. # Add a SVG Header and footer to the svg output from shapely
  4840. # The transform flips the Y Axis so that everything renders
  4841. # properly within svg apps such as inkscape
  4842. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4843. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4844. svg_header += 'width="' + svgwidth + uom + '" '
  4845. svg_header += 'height="' + svgheight + uom + '" '
  4846. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4847. svg_header += '<g transform="scale(1,-1)">'
  4848. svg_footer = '</g> </svg>'
  4849. svg_elem = svg_header + exported_svg + svg_footer
  4850. # Parse the xml through a xml parser just to add line feeds
  4851. # and to make it look more pretty for the output
  4852. svgcode = parse_xml_string(svg_elem)
  4853. with open(filename, 'w') as fp:
  4854. fp.write(svgcode.toprettyxml())
  4855. self.file_saved.emit("SVG", filename)
  4856. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  4857. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4858. """
  4859. Exports a Geometry Object to an SVG file in negative.
  4860. :param filename: Path to the SVG file to save to.
  4861. :param: use_thread: If True use threads
  4862. :type: Bool
  4863. :return:
  4864. """
  4865. self.report_usage("export_negative()")
  4866. if filename is None:
  4867. filename = self.defaults["global_last_save_folder"]
  4868. self.log.debug("export_svg() negative")
  4869. try:
  4870. obj = self.collection.get_by_name(str(obj_name))
  4871. except:
  4872. # TODO: The return behavior has not been established... should raise exception?
  4873. return "Could not retrieve object: %s" % obj_name
  4874. try:
  4875. box = self.collection.get_by_name(str(box_name))
  4876. except:
  4877. # TODO: The return behavior has not been established... should raise exception?
  4878. return "Could not retrieve object: %s" % box_name
  4879. if box is None:
  4880. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  4881. box = obj
  4882. def make_negative_film():
  4883. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4884. self.progress.emit(40)
  4885. # Determine bounding area for svg export
  4886. bounds = box.bounds()
  4887. size = box.size()
  4888. uom = obj.units.lower()
  4889. # Convert everything to strings for use in the xml doc
  4890. svgwidth = str(size[0] + (2 * boundary))
  4891. svgheight = str(size[1] + (2 * boundary))
  4892. minx = str(bounds[0] - boundary)
  4893. miny = str(bounds[1] + boundary + size[1])
  4894. miny_rect = str(bounds[1] - boundary)
  4895. # Add a SVG Header and footer to the svg output from shapely
  4896. # The transform flips the Y Axis so that everything renders
  4897. # properly within svg apps such as inkscape
  4898. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4899. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4900. svg_header += 'width="' + svgwidth + uom + '" '
  4901. svg_header += 'height="' + svgheight + uom + '" '
  4902. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4903. svg_header += '>'
  4904. svg_header += '<g transform="scale(1,-1)">'
  4905. svg_footer = '</g> </svg>'
  4906. self.progress.emit(60)
  4907. # Change the attributes of the exported SVG
  4908. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4909. # We set opacity to maximum
  4910. # We set the color to WHITE
  4911. root = ET.fromstring(exported_svg)
  4912. for child in root:
  4913. child.set('fill', '#FFFFFF')
  4914. child.set('opacity', '1.0')
  4915. child.set('stroke', '#FFFFFF')
  4916. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4917. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4918. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4919. first_svg_elem_tag = 'rect'
  4920. first_svg_elem_attribs = {
  4921. 'x': minx,
  4922. 'y': miny_rect,
  4923. 'width': svgwidth,
  4924. 'height': svgheight,
  4925. 'id': 'neg_rect',
  4926. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4927. }
  4928. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4929. exported_svg = ET.tostring(root)
  4930. svg_elem = svg_header + str(exported_svg) + svg_footer
  4931. self.progress.emit(80)
  4932. # Parse the xml through a xml parser just to add line feeds
  4933. # and to make it look more pretty for the output
  4934. doc = parse_xml_string(svg_elem)
  4935. with open(filename, 'w') as fp:
  4936. fp.write(doc.toprettyxml())
  4937. self.progress.emit(100)
  4938. self.file_saved.emit("SVG", filename)
  4939. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  4940. if use_thread is True:
  4941. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  4942. def job_thread_film(app_obj):
  4943. try:
  4944. make_negative_film()
  4945. except Exception as e:
  4946. proc.done()
  4947. return
  4948. proc.done()
  4949. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4950. else:
  4951. make_negative_film()
  4952. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4953. """
  4954. Exports a Geometry Object to an SVG file in negative.
  4955. :param filename: Path to the SVG file to save to.
  4956. :param: use_thread: If True use threads
  4957. :type: Bool
  4958. :return:
  4959. """
  4960. self.report_usage("export_svg_black()")
  4961. if filename is None:
  4962. filename = self.defaults["global_last_save_folder"]
  4963. self.log.debug("export_svg() black")
  4964. try:
  4965. obj = self.collection.get_by_name(str(obj_name))
  4966. except:
  4967. # TODO: The return behavior has not been established... should raise exception?
  4968. return "Could not retrieve object: %s" % obj_name
  4969. try:
  4970. box = self.collection.get_by_name(str(box_name))
  4971. except:
  4972. # TODO: The return behavior has not been established... should raise exception?
  4973. return "Could not retrieve object: %s" % box_name
  4974. if box is None:
  4975. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  4976. box = obj
  4977. def make_black_film():
  4978. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4979. self.progress.emit(40)
  4980. # Change the attributes of the exported SVG
  4981. # We don't need stroke-width
  4982. # We set opacity to maximum
  4983. # We set the colour to WHITE
  4984. root = ET.fromstring(exported_svg)
  4985. for child in root:
  4986. child.set('fill', '#000000')
  4987. child.set('opacity', '1.0')
  4988. child.set('stroke', '#000000')
  4989. exported_svg = ET.tostring(root)
  4990. # Determine bounding area for svg export
  4991. bounds = box.bounds()
  4992. size = box.size()
  4993. # This contain the measure units
  4994. uom = obj.units.lower()
  4995. # Define a boundary around SVG of about 1.0mm (~39mils)
  4996. if uom in "mm":
  4997. boundary = 1.0
  4998. else:
  4999. boundary = 0.0393701
  5000. self.progress.emit(80)
  5001. # Convert everything to strings for use in the xml doc
  5002. svgwidth = str(size[0] + (2 * boundary))
  5003. svgheight = str(size[1] + (2 * boundary))
  5004. minx = str(bounds[0] - boundary)
  5005. miny = str(bounds[1] + boundary + size[1])
  5006. self.log.debug(minx)
  5007. self.log.debug(miny)
  5008. # Add a SVG Header and footer to the svg output from shapely
  5009. # The transform flips the Y Axis so that everything renders
  5010. # properly within svg apps such as inkscape
  5011. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5012. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5013. svg_header += 'width="' + svgwidth + uom + '" '
  5014. svg_header += 'height="' + svgheight + uom + '" '
  5015. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5016. svg_header += '>'
  5017. svg_header += '<g transform="scale(1,-1)">'
  5018. svg_footer = '</g> </svg>'
  5019. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5020. self.progress.emit(90)
  5021. # Parse the xml through a xml parser just to add line feeds
  5022. # and to make it look more pretty for the output
  5023. doc = parse_xml_string(svg_elem)
  5024. with open(filename, 'w') as fp:
  5025. fp.write(doc.toprettyxml())
  5026. self.progress.emit(100)
  5027. self.file_saved.emit("SVG", filename)
  5028. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5029. if use_thread is True:
  5030. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5031. def job_thread_film(app_obj):
  5032. try:
  5033. make_black_film()
  5034. except Exception as e:
  5035. proc.done()
  5036. return
  5037. proc.done()
  5038. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5039. else:
  5040. make_black_film()
  5041. def save_source_file(self, obj_name, filename, use_thread=True):
  5042. """
  5043. Exports a Gerber Object to an Gerber file.
  5044. :param filename: Path to the Gerber file to save to.
  5045. :return:
  5046. """
  5047. self.report_usage("save source file()")
  5048. if filename is None:
  5049. filename = self.defaults["global_last_save_folder"]
  5050. self.log.debug("save source file()")
  5051. obj = self.collection.get_by_name(obj_name)
  5052. file_string = StringIO(obj.source_file)
  5053. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5054. with open(filename, 'w') as file:
  5055. file.writelines('G04*\n')
  5056. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5057. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5058. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5059. file.writelines('G04 Created on : %s*\n' % time_string)
  5060. for line in file_string:
  5061. file.writelines(line)
  5062. def export_excellon(self, obj_name, filename, use_thread=True):
  5063. """
  5064. Exports a Excellon Object to an Excellon file.
  5065. :param filename: Path to the Excellon file to save to.
  5066. :return:
  5067. """
  5068. self.report_usage("export_excellon()")
  5069. if filename is None:
  5070. filename = self.defaults["global_last_save_folder"]
  5071. self.log.debug("export_excellon()")
  5072. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5073. self.defaults["excellon_exp_decimals"]
  5074. )
  5075. units = ''
  5076. try:
  5077. obj = self.collection.get_by_name(str(obj_name))
  5078. except:
  5079. # TODO: The return behavior has not been established... should raise exception?
  5080. return "Could not retrieve object: %s" % obj_name
  5081. # updated units
  5082. eunits = self.defaults["excellon_exp_units"]
  5083. ewhole = self.defaults["excellon_exp_integer"]
  5084. efract = self.defaults["excellon_exp_decimals"]
  5085. ezeros = self.defaults["excellon_exp_zeros"]
  5086. eformat = self.defaults[ "excellon_exp_format"]
  5087. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5088. if fc_units == 'MM':
  5089. factor = 1 if eunits == 'METRIC' else 0.03937
  5090. else:
  5091. factor = 25.4 if eunits == 'METRIC' else 1
  5092. def make_excellon():
  5093. try:
  5094. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5095. header = 'M48\n'
  5096. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5097. (str(self.version), str(self.version_date))
  5098. header += ';Filename: %s' % str(obj_name) + '\n'
  5099. header += ';Created on : %s' % time_str + '\n'
  5100. if eformat == 'dec':
  5101. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5102. header += eunits + '\n'
  5103. for tool in obj.tools:
  5104. if eunits == 'METRIC':
  5105. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5106. tool=str(tool),
  5107. dec=2)
  5108. else:
  5109. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5110. tool=str(tool),
  5111. dec=4)
  5112. else:
  5113. if ezeros == 'LZ':
  5114. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5115. form='ndec', e_zeros='LZ', factor=factor)
  5116. header += '%s,%s\n' % (eunits, 'LZ')
  5117. header += format_exc
  5118. for tool in obj.tools:
  5119. if eunits == 'METRIC':
  5120. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5121. tool=str(tool),
  5122. dec=2)
  5123. else:
  5124. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5125. tool=str(tool),
  5126. dec=4)
  5127. else:
  5128. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5129. form='ndec', e_zeros='TZ', factor=factor)
  5130. header += '%s,%s\n' % (eunits, 'TZ')
  5131. header += format_exc
  5132. for tool in obj.tools:
  5133. if eunits == 'METRIC':
  5134. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5135. tool=str(tool),
  5136. dec=2)
  5137. else:
  5138. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5139. tool=str(tool),
  5140. dec=4)
  5141. header += '%\n'
  5142. footer = 'M30\n'
  5143. exported_excellon = header
  5144. exported_excellon += excellon_code
  5145. exported_excellon += footer
  5146. with open(filename, 'w') as fp:
  5147. fp.write(exported_excellon)
  5148. self.file_saved.emit("Excellon", filename)
  5149. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5150. except Exception as e:
  5151. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5152. return 'fail'
  5153. if use_thread is True:
  5154. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5155. def job_thread_exc(app_obj):
  5156. ret = make_excellon()
  5157. if ret == 'fail':
  5158. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5159. return
  5160. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5161. else:
  5162. ret = make_excellon()
  5163. if ret == 'fail':
  5164. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5165. return
  5166. def export_dxf(self, obj_name, filename, use_thread=True):
  5167. """
  5168. Exports a Geometry Object to an DXF file.
  5169. :param filename: Path to the DXF file to save to.
  5170. :return:
  5171. """
  5172. self.report_usage("export_dxf()")
  5173. if filename is None:
  5174. filename = self.defaults["global_last_save_folder"]
  5175. self.log.debug("export_dxf()")
  5176. format_exc = ''
  5177. units = ''
  5178. try:
  5179. obj = self.collection.get_by_name(str(obj_name))
  5180. except:
  5181. # TODO: The return behavior has not been established... should raise exception?
  5182. return "Could not retrieve object: %s" % obj_name
  5183. # updated units
  5184. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5185. if units == 'IN' or units == 'INCH':
  5186. units = 'INCH'
  5187. elif units == 'MM' or units == 'METIRC':
  5188. units ='METRIC'
  5189. def make_dxf():
  5190. try:
  5191. dxf_code = obj.export_dxf()
  5192. dxf_code.saveas(filename)
  5193. self.file_saved.emit("DXF", filename)
  5194. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5195. except:
  5196. return 'fail'
  5197. if use_thread is True:
  5198. with self.proc_container.new(_("Exporting DXF")) as proc:
  5199. def job_thread_exc(app_obj):
  5200. ret = make_dxf()
  5201. if ret == 'fail':
  5202. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5203. return
  5204. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5205. else:
  5206. ret = make_dxf()
  5207. if ret == 'fail':
  5208. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5209. return
  5210. def import_svg(self, filename, geo_type='geometry', outname=None):
  5211. """
  5212. Adds a new Geometry Object to the projects and populates
  5213. it with shapes extracted from the SVG file.
  5214. :param filename: Path to the SVG file.
  5215. :param outname:
  5216. :return:
  5217. """
  5218. self.report_usage("import_svg()")
  5219. obj_type = ""
  5220. if geo_type is None or geo_type == "geometry":
  5221. obj_type = "geometry"
  5222. elif geo_type == "gerber":
  5223. obj_type = geo_type
  5224. else:
  5225. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5226. "Only Geometry and Gerber are supported"))
  5227. return
  5228. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5229. def obj_init(geo_obj, app_obj):
  5230. geo_obj.import_svg(filename, obj_type, units=units)
  5231. geo_obj.multigeo = False
  5232. with self.proc_container.new(_("Importing SVG")) as proc:
  5233. # Object name
  5234. name = outname or filename.split('/')[-1].split('\\')[-1]
  5235. self.new_object(obj_type, name, obj_init, autoselected=False)
  5236. self.progress.emit(20)
  5237. # Register recent file
  5238. self.file_opened.emit("svg", filename)
  5239. # GUI feedback
  5240. self.inform.emit(_("[success] Opened: %s") % filename)
  5241. self.progress.emit(100)
  5242. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5243. """
  5244. Adds a new Geometry Object to the projects and populates
  5245. it with shapes extracted from the DXF file.
  5246. :param filename: Path to the DXF file.
  5247. :param outname:
  5248. :type putname: str
  5249. :return:
  5250. """
  5251. self.report_usage("import_dxf()")
  5252. obj_type = ""
  5253. if geo_type is None or geo_type == "geometry":
  5254. obj_type = "geometry"
  5255. elif geo_type == "gerber":
  5256. obj_type = geo_type
  5257. else:
  5258. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5259. "Only Geometry and Gerber are supported"))
  5260. return
  5261. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5262. def obj_init(geo_obj, app_obj):
  5263. geo_obj.import_dxf(filename, obj_type, units=units)
  5264. geo_obj.multigeo = False
  5265. with self.proc_container.new(_("Importing DXF")) as proc:
  5266. # Object name
  5267. name = outname or filename.split('/')[-1].split('\\')[-1]
  5268. self.new_object(obj_type, name, obj_init, autoselected=False)
  5269. self.progress.emit(20)
  5270. # Register recent file
  5271. self.file_opened.emit("dxf", filename)
  5272. # GUI feedback
  5273. self.inform.emit(_("[success] Opened: %s") % filename)
  5274. self.progress.emit(100)
  5275. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5276. """
  5277. Adds a new Geometry Object to the projects and populates
  5278. it with shapes extracted from the SVG file.
  5279. :param filename: Path to the SVG file.
  5280. :param outname:
  5281. :return:
  5282. """
  5283. self.report_usage("import_image()")
  5284. obj_type = ""
  5285. if type is None or type == "geometry":
  5286. obj_type = "geometry"
  5287. elif type == "gerber":
  5288. obj_type = type
  5289. else:
  5290. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5291. "Only Geometry and Gerber are supported"))
  5292. return
  5293. def obj_init(geo_obj, app_obj):
  5294. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5295. geo_obj.multigeo = False
  5296. with self.proc_container.new(_("Importing Image")) as proc:
  5297. # Object name
  5298. name = outname or filename.split('/')[-1].split('\\')[-1]
  5299. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5300. self.new_object(obj_type, name, obj_init)
  5301. self.progress.emit(20)
  5302. # Register recent file
  5303. self.file_opened.emit("image", filename)
  5304. # GUI feedback
  5305. self.inform.emit(_("[success] Opened: %s") % filename)
  5306. self.progress.emit(100)
  5307. def open_gerber(self, filename, outname=None):
  5308. """
  5309. Opens a Gerber file, parses it and creates a new object for
  5310. it in the program. Thread-safe.
  5311. :param outname: Name of the resulting object. None causes the
  5312. name to be that of the file.
  5313. :param filename: Gerber file filename
  5314. :type filename: str
  5315. :param follow: If true, the parser will not create polygons, just lines
  5316. following the gerber path.
  5317. :type follow: bool
  5318. :return: None
  5319. """
  5320. # How the object should be initialized
  5321. def obj_init(gerber_obj, app_obj):
  5322. assert isinstance(gerber_obj, FlatCAMGerber), \
  5323. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5324. # Opening the file happens here
  5325. self.progress.emit(30)
  5326. try:
  5327. gerber_obj.parse_file(filename)
  5328. except IOError:
  5329. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5330. app_obj.progress.emit(0)
  5331. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5332. return "fail"
  5333. except ParseError as err:
  5334. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: %s. %s") % (filename, str(err)))
  5335. app_obj.progress.emit(0)
  5336. self.log.error(str(err))
  5337. return "fail"
  5338. except:
  5339. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5340. msg += traceback.format_exc()
  5341. app_obj.inform.emit(msg)
  5342. return "fail"
  5343. if gerber_obj.is_empty():
  5344. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5345. # self.collection.set_active(gerber_obj.options["name"])
  5346. # self.collection.delete_active()
  5347. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5348. return "fail"
  5349. # Further parsing
  5350. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5351. App.log.debug("open_gerber()")
  5352. with self.proc_container.new(_("Opening Gerber")) as proc:
  5353. self.progress.emit(10)
  5354. # Object name
  5355. name = outname or filename.split('/')[-1].split('\\')[-1]
  5356. ### Object creation ###
  5357. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5358. if ret == 'fail':
  5359. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5360. return
  5361. # Register recent file
  5362. self.file_opened.emit("gerber", filename)
  5363. self.progress.emit(100)
  5364. # GUI feedback
  5365. self.inform.emit(_("[success] Opened: %s") % filename)
  5366. def open_excellon(self, filename, outname=None):
  5367. """
  5368. Opens an Excellon file, parses it and creates a new object for
  5369. it in the program. Thread-safe.
  5370. :param outname: Name of the resulting object. None causes the
  5371. name to be that of the file.
  5372. :param filename: Excellon file filename
  5373. :type filename: str
  5374. :return: None
  5375. """
  5376. App.log.debug("open_excellon()")
  5377. #self.progress.emit(10)
  5378. # How the object should be initialized
  5379. def obj_init(excellon_obj, app_obj):
  5380. # self.progress.emit(20)
  5381. try:
  5382. ret = excellon_obj.parse_file(filename)
  5383. if ret == "fail":
  5384. log.debug("Excellon parsing failed.")
  5385. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5386. return "fail"
  5387. except IOError:
  5388. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5389. log.debug("Could not open Excellon object.")
  5390. self.progress.emit(0) # TODO: self and app_bjj mixed
  5391. return "fail"
  5392. except:
  5393. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5394. msg += traceback.format_exc()
  5395. app_obj.inform.emit(msg)
  5396. return "fail"
  5397. ret = excellon_obj.create_geometry()
  5398. if ret == 'fail':
  5399. log.debug("Could not create geometry for Excellon object.")
  5400. return "fail"
  5401. # if excellon_obj.is_empty():
  5402. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5403. # return "fail"
  5404. for tool in excellon_obj.tools:
  5405. if excellon_obj.tools[tool]['solid_geometry']:
  5406. return
  5407. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5408. return "fail"
  5409. with self.proc_container.new(_("Opening Excellon.")):
  5410. # Object name
  5411. name = outname or filename.split('/')[-1].split('\\')[-1]
  5412. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5413. if ret == 'fail':
  5414. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5415. return
  5416. # Register recent file
  5417. self.file_opened.emit("excellon", filename)
  5418. # GUI feedback
  5419. self.inform.emit(_("[success] Opened: %s") % filename)
  5420. # self.progress.emit(100)
  5421. def open_gcode(self, filename, outname=None):
  5422. """
  5423. Opens a G-gcode file, parses it and creates a new object for
  5424. it in the program. Thread-safe.
  5425. :param outname: Name of the resulting object. None causes the
  5426. name to be that of the file.
  5427. :param filename: G-code file filename
  5428. :type filename: str
  5429. :return: None
  5430. """
  5431. App.log.debug("open_gcode()")
  5432. # How the object should be initialized
  5433. def obj_init(job_obj, app_obj_):
  5434. """
  5435. :type app_obj_: App
  5436. """
  5437. assert isinstance(app_obj_, App), \
  5438. "Initializer expected App, got %s" % type(app_obj_)
  5439. self.progress.emit(10)
  5440. try:
  5441. f = open(filename)
  5442. gcode = f.read()
  5443. f.close()
  5444. except IOError:
  5445. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5446. self.progress.emit(0)
  5447. return "fail"
  5448. job_obj.gcode = gcode
  5449. self.progress.emit(20)
  5450. ret = job_obj.gcode_parse()
  5451. if ret == "fail":
  5452. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5453. return "fail"
  5454. self.progress.emit(60)
  5455. job_obj.create_geometry()
  5456. with self.proc_container.new(_("Opening G-Code.")):
  5457. # Object name
  5458. name = outname or filename.split('/')[-1].split('\\')[-1]
  5459. # New object creation and file processing
  5460. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5461. if ret == 'fail':
  5462. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5463. "Attempting to create a FlatCAM CNCJob Object from "
  5464. "G-Code file failed during processing"))
  5465. return "fail"
  5466. # Register recent file
  5467. self.file_opened.emit("cncjob", filename)
  5468. # GUI feedback
  5469. self.inform.emit(_("[success] Opened: %s") % filename)
  5470. self.progress.emit(100)
  5471. def open_config_file(self, filename, run_from_arg=None):
  5472. """
  5473. Loads a config file from the specified file.
  5474. :param filename: Name of the file from which to load.
  5475. :type filename: str
  5476. :return: None
  5477. """
  5478. App.log.debug("Opening config file: " + filename)
  5479. # add the tab if it was closed
  5480. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5481. # first clear previous text in text editor (if any)
  5482. self.ui.code_editor.clear()
  5483. # Switch plot_area to CNCJob tab
  5484. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5485. try:
  5486. if filename:
  5487. f = QtCore.QFile(filename)
  5488. if f.open(QtCore.QIODevice.ReadOnly):
  5489. stream = QtCore.QTextStream(f)
  5490. gcode_edited = stream.readAll()
  5491. self.ui.code_editor.setPlainText(gcode_edited)
  5492. f.close()
  5493. except IOError:
  5494. App.log.error("Failed to open config file: %s" % filename)
  5495. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5496. return
  5497. def open_project(self, filename, run_from_arg=None):
  5498. """
  5499. Loads a project from the specified file.
  5500. 1) Loads and parses file
  5501. 2) Registers the file as recently opened.
  5502. 3) Calls on_file_new()
  5503. 4) Updates options
  5504. 5) Calls new_object() with the object's from_dict() as init method.
  5505. 6) Calls plot_all()
  5506. :param filename: Name of the file from which to load.
  5507. :type filename: str
  5508. :return: None
  5509. """
  5510. App.log.debug("Opening project: " + filename)
  5511. # Open and parse an uncompressed Project file
  5512. try:
  5513. f = open(filename, 'r')
  5514. except IOError:
  5515. App.log.error("Failed to open project file: %s" % filename)
  5516. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5517. return
  5518. try:
  5519. d = json.load(f, object_hook=dict2obj)
  5520. except:
  5521. App.log.error("Failed to parse project file: %s" % filename)
  5522. self.inform.emit(_("[ERROR_NOTCL] Failed to parse project file: %s") % filename)
  5523. f.close()
  5524. # Open and parse a compressed Project file
  5525. try:
  5526. with lzma.open(filename) as f:
  5527. file_content = f.read().decode('utf-8')
  5528. d = json.loads(file_content, object_hook=dict2obj)
  5529. except IOError:
  5530. App.log.error("Failed to open project file: %s" % filename)
  5531. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5532. return
  5533. self.file_opened.emit("project", filename)
  5534. # Clear the current project
  5535. ## NOT THREAD SAFE ##
  5536. if run_from_arg is True:
  5537. pass
  5538. else:
  5539. self.on_file_new()
  5540. #Project options
  5541. self.options.update(d['options'])
  5542. self.project_filename = filename
  5543. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5544. self.set_screen_units(self.options["units"])
  5545. # Re create objects
  5546. App.log.debug("Re-creating objects...")
  5547. for obj in d['objs']:
  5548. def obj_init(obj_inst, app_inst):
  5549. obj_inst.from_dict(obj)
  5550. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5551. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5552. self.plot_all()
  5553. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  5554. self.should_we_save = False
  5555. App.log.debug("Project loaded")
  5556. def propagate_defaults(self, silent=False):
  5557. """
  5558. This method is used to set default values in classes. It's
  5559. an alternative to project options but allows the use
  5560. of values invisible to the user.
  5561. :return: None
  5562. """
  5563. if silent is False:
  5564. self.log.debug("propagate_defaults()")
  5565. # Which objects to update the given parameters.
  5566. routes = {
  5567. "global_zdownrate": CNCjob,
  5568. "excellon_zeros": Excellon,
  5569. "excellon_format_upper_in": Excellon,
  5570. "excellon_format_lower_in": Excellon,
  5571. "excellon_format_upper_mm": Excellon,
  5572. "excellon_format_lower_mm": Excellon,
  5573. "excellon_units": Excellon,
  5574. "gerber_use_buffer_for_union": Gerber,
  5575. "geometry_multidepth": Geometry
  5576. }
  5577. for param in routes:
  5578. if param in routes[param].defaults:
  5579. try:
  5580. routes[param].defaults[param] = self.defaults[param]
  5581. if silent is False:
  5582. self.log.debug(" " + param + " OK")
  5583. except KeyError:
  5584. if silent is False:
  5585. self.log.debug(" ERROR: " + param + " not in defaults.")
  5586. else:
  5587. # Try extracting the name:
  5588. # classname_param here is param in the object
  5589. if param.find(routes[param].__name__.lower() + "_") == 0:
  5590. p = param[len(routes[param].__name__) + 1:]
  5591. if p in routes[param].defaults:
  5592. routes[param].defaults[p] = self.defaults[param]
  5593. if silent is False:
  5594. self.log.debug(" " + param + " OK!")
  5595. def restore_main_win_geom(self):
  5596. try:
  5597. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5598. self.defaults["global_def_win_y"],
  5599. self.defaults["global_def_win_w"],
  5600. self.defaults["global_def_win_h"])
  5601. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5602. settings = QSettings("Open Source", "FlatCAM")
  5603. if settings.contains("maximized_gui"):
  5604. maximized_ui = settings.value('maximized_gui', type=bool)
  5605. if maximized_ui is True:
  5606. self.ui.showMaximized()
  5607. except KeyError:
  5608. pass
  5609. def plot_all(self, zoom=True):
  5610. """
  5611. Re-generates all plots from all objects.
  5612. :return: None
  5613. """
  5614. self.log.debug("Plot_all()")
  5615. for obj in self.collection.get_list():
  5616. def worker_task(obj):
  5617. with self.proc_container.new("Plotting"):
  5618. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5619. if zoom:
  5620. self.object_plotted.emit(obj)
  5621. # Send to worker
  5622. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5623. # self.progress.emit(10)
  5624. #
  5625. # def worker_task(app_obj):
  5626. # print "worker task"
  5627. # percentage = 0.1
  5628. # try:
  5629. # delta = 0.9 / len(self.collection.get_list())
  5630. # except ZeroDivisionError:
  5631. # self.progress.emit(0)
  5632. # return
  5633. # for obj in self.collection.get_list():
  5634. # with self.proc_container.new("Plotting"):
  5635. # obj.plot()
  5636. # app_obj.object_plotted.emit(obj)
  5637. #
  5638. # percentage += delta
  5639. # self.progress.emit(int(percentage*100))
  5640. #
  5641. # self.progress.emit(0)
  5642. # self.plots_updated.emit()
  5643. #
  5644. # # Send to worker
  5645. # #self.worker.add_task(worker_task, [self])
  5646. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5647. def register_folder(self, filename):
  5648. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5649. def register_save_folder(self, filename):
  5650. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5651. def set_progress_bar(self, percentage, text=""):
  5652. self.ui.progress_bar.setValue(int(percentage))
  5653. def setup_shell(self):
  5654. """
  5655. Creates shell functions. Runs once at startup.
  5656. :return: None
  5657. """
  5658. self.log.debug("setup_shell()")
  5659. def shelp(p=None):
  5660. if not p:
  5661. return _("Available commands:\n") + \
  5662. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5663. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  5664. if p not in commands:
  5665. return "Unknown command: %s" % p
  5666. return commands[p]["help"]
  5667. # --- Migrated to new architecture ---
  5668. # def options(name):
  5669. # ops = self.collection.get_by_name(str(name)).options
  5670. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5671. def h(*args):
  5672. """
  5673. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5674. and standalone parameters into list.
  5675. """
  5676. kwa = {}
  5677. a = []
  5678. n = len(args)
  5679. name = None
  5680. for i in range(n):
  5681. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5682. if match:
  5683. assert name is None
  5684. name = match.group(1)
  5685. continue
  5686. if name is None:
  5687. a.append(args[i])
  5688. else:
  5689. kwa[name] = args[i]
  5690. name = None
  5691. return a, kwa
  5692. @contextmanager
  5693. def wait_signal(signal, timeout=10000):
  5694. """
  5695. Block loop until signal emitted, timeout (ms) elapses
  5696. or unhandled exception happens in a thread.
  5697. :param signal: Signal to wait for.
  5698. """
  5699. loop = QtCore.QEventLoop()
  5700. # Normal termination
  5701. signal.connect(loop.quit)
  5702. # Termination by exception in thread
  5703. self.thread_exception.connect(loop.quit)
  5704. status = {'timed_out': False}
  5705. def report_quit():
  5706. status['timed_out'] = True
  5707. loop.quit()
  5708. yield
  5709. # Temporarily change how exceptions are managed.
  5710. oeh = sys.excepthook
  5711. ex = []
  5712. def except_hook(type_, value, traceback_):
  5713. ex.append(value)
  5714. oeh(type_, value, traceback_)
  5715. sys.excepthook = except_hook
  5716. # Terminate on timeout
  5717. if timeout is not None:
  5718. QtCore.QTimer.singleShot(timeout, report_quit)
  5719. #### Block ####
  5720. loop.exec_()
  5721. # Restore exception management
  5722. sys.excepthook = oeh
  5723. if ex:
  5724. self.raiseTclError(str(ex[0]))
  5725. if status['timed_out']:
  5726. raise Exception('Timed out!')
  5727. def make_docs():
  5728. output = ''
  5729. import collections
  5730. od = collections.OrderedDict(sorted(commands.items()))
  5731. for cmd_, val in od.items():
  5732. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5733. t = val['help']
  5734. usage_i = t.find('>')
  5735. if usage_i < 0:
  5736. expl = t
  5737. output += expl + '\n\n'
  5738. continue
  5739. expl = t[:usage_i - 1]
  5740. output += expl + '\n\n'
  5741. end_usage_i = t[usage_i:].find('\n')
  5742. if end_usage_i < 0:
  5743. end_usage_i = len(t[usage_i:])
  5744. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5745. else:
  5746. extras = t[usage_i+end_usage_i+1:]
  5747. parts = [s.strip() for s in extras.split('\n')]
  5748. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5749. for p in parts:
  5750. output += ' ' + p + '\n\n'
  5751. return output
  5752. '''
  5753. Howto implement TCL shell commands:
  5754. All parameters passed to command should be possible to set as None and test it afterwards.
  5755. This is because we need to see error caused in tcl,
  5756. if None value as default parameter is not allowed TCL will return empty error.
  5757. Use:
  5758. def mycommand(name=None,...):
  5759. Test it like this:
  5760. if name is None:
  5761. self.raise_tcl_error('Argument name is missing.')
  5762. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5763. otherwise we will miss it and processing will silently continue.
  5764. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5765. which is catched in exec_command and displayed in TCL shell console with red background.
  5766. Error in console is displayed with TCL trace.
  5767. This behavior works only within main thread,
  5768. errors with promissed tasks can be catched and detected only with log.
  5769. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5770. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5771. '''
  5772. commands = {
  5773. 'help': {
  5774. 'fcn': shelp,
  5775. 'help': _("Shows list of commands.")
  5776. },
  5777. }
  5778. # Import/overwrite tcl commands as objects of TclCommand descendants
  5779. # This modifies the variable 'commands'.
  5780. tclCommands.register_all_commands(self, commands)
  5781. # Add commands to the tcl interpreter
  5782. for cmd in commands:
  5783. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5784. # Make the tcl puts function return instead of print to stdout
  5785. self.tcl.eval('''
  5786. rename puts original_puts
  5787. proc puts {args} {
  5788. if {[llength $args] == 1} {
  5789. return "[lindex $args 0]"
  5790. } else {
  5791. eval original_puts $args
  5792. }
  5793. }
  5794. ''')
  5795. def setup_recent_items(self):
  5796. # TODO: Move this to constructor
  5797. icons = {
  5798. "gerber": "share/flatcam_icon16.png",
  5799. "excellon": "share/drill16.png",
  5800. "cncjob": "share/cnc16.png",
  5801. "project": "share/project16.png",
  5802. "svg": "share/geometry16.png",
  5803. "dxf": "share/dxf16.png",
  5804. "image": "share/image16.png"
  5805. }
  5806. openers = {
  5807. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5808. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5809. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5810. 'project': self.open_project,
  5811. 'svg': self.import_svg,
  5812. 'dxf': self.import_dxf,
  5813. 'image': self.import_image
  5814. }
  5815. # Open file
  5816. try:
  5817. f = open(self.data_path + '/recent.json')
  5818. except IOError:
  5819. App.log.error("Failed to load recent item list.")
  5820. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  5821. return
  5822. try:
  5823. self.recent = json.load(f)
  5824. except json.scanner.JSONDecodeError:
  5825. App.log.error("Failed to parse recent item list.")
  5826. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  5827. f.close()
  5828. return
  5829. f.close()
  5830. # Closure needed to create callbacks in a loop.
  5831. # Otherwise late binding occurs.
  5832. def make_callback(func, fname):
  5833. def opener():
  5834. func(fname)
  5835. return opener
  5836. def reset_recent():
  5837. # Reset menu
  5838. self.ui.recent.clear()
  5839. self.recent = []
  5840. try:
  5841. f = open(self.data_path + '/recent.json', 'w')
  5842. except IOError:
  5843. App.log.error("Failed to open recent items file for writing.")
  5844. return
  5845. json.dump(self.recent, f)
  5846. # Reset menu
  5847. self.ui.recent.clear()
  5848. # Create menu items
  5849. for recent in self.recent:
  5850. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5851. try:
  5852. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5853. # Attach callback
  5854. o = make_callback(openers[recent["kind"]], recent['filename'])
  5855. action.triggered.connect(o)
  5856. self.ui.recent.addAction(action)
  5857. except KeyError:
  5858. App.log.error("Unsupported file type: %s" % recent["kind"])
  5859. # Last action in Recent Files menu is one that Clear the content
  5860. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5861. clear_action.triggered.connect(reset_recent)
  5862. self.ui.recent.addSeparator()
  5863. self.ui.recent.addAction(clear_action)
  5864. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5865. # self.ui.menufilerecent.set_submenu(recent_menu)
  5866. # recent_menu.show_all()
  5867. # self.ui.recent.show()
  5868. self.log.debug("Recent items list has been populated.")
  5869. def setup_component_editor(self):
  5870. # label = QtWidgets.QLabel("Choose an item from Project")
  5871. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5872. sel_title = QtWidgets.QTextEdit(
  5873. _('<b>Shortcut Key List</b>'))
  5874. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5875. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5876. # font = self.sel_title.font()
  5877. # font.setPointSize(12)
  5878. # self.sel_title.setFont(font)
  5879. selected_text = _('''
  5880. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5881. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5882. The normal flow when working in FlatCAM is the following:</span></p>
  5883. <ol>
  5884. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5885. <br />
  5886. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5887. &nbsp;</li>
  5888. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5889. <br />
  5890. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5891. <br />
  5892. You can change the parameters in this screen and the flow direction is like this:<br />
  5893. <br />
  5894. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5895. </ol>
  5896. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5897. ''')
  5898. sel_title.setText(selected_text)
  5899. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5900. self.ui.selected_scroll_area.setWidget(sel_title)
  5901. # tool_title = QtWidgets.QTextEdit(
  5902. # '<b>Shortcut Key List</b>')
  5903. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5904. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5905. # # font = self.sel_title.font()
  5906. # # font.setPointSize(12)
  5907. # # self.sel_title.setFont(font)
  5908. #
  5909. # tool_text = '''
  5910. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5911. #
  5912. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5913. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5914. #
  5915. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5916. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5917. #
  5918. # <ol>
  5919. # </ol>
  5920. #
  5921. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5922. #
  5923. # '''
  5924. #
  5925. # tool_title.setText(tool_text)
  5926. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5927. #
  5928. # self.ui.tool_scroll_area.setWidget(tool_title)
  5929. def setup_obj_classes(self):
  5930. """
  5931. Sets up application specifics on the FlatCAMObj class.
  5932. :return: None
  5933. """
  5934. FlatCAMObj.app = self
  5935. ObjectCollection.app = self
  5936. FCProcess.app = self
  5937. FCProcessContainer.app = self
  5938. def version_check(self):
  5939. """
  5940. Checks for the latest version of the program. Alerts the
  5941. user if theirs is outdated. This method is meant to be run
  5942. in a separate thread.
  5943. :return: None
  5944. """
  5945. self.log.debug("version_check()")
  5946. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5947. full_url = App.version_url + \
  5948. "?s=" + str(self.defaults['global_serial']) + \
  5949. "&v=" + str(self.version) + \
  5950. "&os=" + str(self.os) + \
  5951. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5952. else:
  5953. # no_stats dict; just so it won't break things on website
  5954. no_ststs_dict = {}
  5955. no_ststs_dict["global_ststs"] = {}
  5956. full_url = App.version_url + \
  5957. "?s=" + str(self.defaults['global_serial']) + \
  5958. "&v=" + str(self.version) + \
  5959. "&os=" + str(self.os) + \
  5960. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5961. App.log.debug("Checking for updates @ %s" % full_url)
  5962. ### Get the data
  5963. try:
  5964. f = urllib.request.urlopen(full_url)
  5965. except:
  5966. # App.log.warning("Failed checking for latest version. Could not connect.")
  5967. self.log.warning("Failed checking for latest version. Could not connect.")
  5968. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  5969. return
  5970. try:
  5971. data = json.load(f)
  5972. except Exception as e:
  5973. App.log.error("Could not parse information about latest version.")
  5974. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  5975. App.log.debug("json.load(): %s" % str(e))
  5976. f.close()
  5977. return
  5978. f.close()
  5979. ### Latest version?
  5980. if self.version >= data["version"]:
  5981. App.log.debug("FlatCAM is up to date!")
  5982. self.inform.emit(_("[success] FlatCAM is up to date!"))
  5983. return
  5984. App.log.debug("Newer version available.")
  5985. self.message.emit(
  5986. _("Newer Version Available"),
  5987. _("There is a newer version of FlatCAM available for download:\n\n") +
  5988. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  5989. _("info")
  5990. )
  5991. def on_zoom_fit(self, event):
  5992. """
  5993. Callback for zoom-out request. This can be either from the corresponding
  5994. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5995. with axes limits from the geometry bounds of all objects.
  5996. :param event: Ignored.
  5997. :return: None
  5998. """
  5999. self.plotcanvas.fit_view()
  6000. def disable_all_plots(self):
  6001. self.report_usage("disable_all_plots()")
  6002. self.disable_plots(self.collection.get_list())
  6003. self.inform.emit(_("[success]All plots disabled."))
  6004. def disable_other_plots(self):
  6005. self.report_usage("disable_other_plots()")
  6006. self.disable_plots(self.collection.get_non_selected())
  6007. self.inform.emit(_("[success]All non selected plots disabled."))
  6008. def enable_all_plots(self):
  6009. self.report_usage("enable_all_plots()")
  6010. self.enable_plots(self.collection.get_list())
  6011. self.inform.emit(_("[success]All plots enabled."))
  6012. # TODO: FIX THIS
  6013. '''
  6014. By default this is not threaded
  6015. If threaded the app give warnings like this:
  6016. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6017. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6018. '''
  6019. def enable_plots(self, objects, threaded=False):
  6020. if threaded is True:
  6021. def worker_task(app_obj):
  6022. percentage = 0.1
  6023. try:
  6024. delta = 0.9 / len(objects)
  6025. except ZeroDivisionError:
  6026. self.progress.emit(0)
  6027. return
  6028. for obj in objects:
  6029. obj.options['plot'] = True
  6030. percentage += delta
  6031. self.progress.emit(int(percentage*100))
  6032. self.progress.emit(0)
  6033. self.plots_updated.emit()
  6034. self.collection.update_view()
  6035. # Send to worker
  6036. # self.worker.add_task(worker_task, [self])
  6037. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6038. else:
  6039. for obj in objects:
  6040. obj.options['plot'] = True
  6041. self.progress.emit(0)
  6042. self.plots_updated.emit()
  6043. self.collection.update_view()
  6044. # TODO: FIX THIS
  6045. '''
  6046. By default this is not threaded
  6047. If threaded the app give warnings like this:
  6048. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6049. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6050. '''
  6051. def disable_plots(self, objects, threaded=False):
  6052. # TODO: This method is very similar to replot_all. Try to merge.
  6053. """
  6054. Disables plots
  6055. :param objects: list
  6056. Objects to be disabled
  6057. :return:
  6058. """
  6059. if threaded is True:
  6060. self.progress.emit(10)
  6061. def worker_task(app_obj):
  6062. percentage = 0.1
  6063. try:
  6064. delta = 0.9 / len(objects)
  6065. except ZeroDivisionError:
  6066. self.progress.emit(0)
  6067. return
  6068. for obj in objects:
  6069. obj.options['plot'] = False
  6070. percentage += delta
  6071. self.progress.emit(int(percentage*100))
  6072. self.progress.emit(0)
  6073. self.plots_updated.emit()
  6074. self.collection.update_view()
  6075. # Send to worker
  6076. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6077. else:
  6078. for obj in objects:
  6079. obj.options['plot'] = False
  6080. self.plots_updated.emit()
  6081. self.collection.update_view()
  6082. def clear_plots(self):
  6083. objects = self.collection.get_list()
  6084. for obj in objects:
  6085. obj.clear(obj == objects[-1])
  6086. # Clear pool to free memory
  6087. self.clear_pool()
  6088. def generate_cnc_job(self, objects):
  6089. self.report_usage("generate_cnc_job()")
  6090. # for obj in objects:
  6091. # obj.generatecncjob()
  6092. for obj in objects:
  6093. obj.on_generatecnc_button_click()
  6094. def save_project(self, filename):
  6095. """
  6096. Saves the current project to the specified file.
  6097. :param filename: Name of the file in which to save.
  6098. :type filename: str
  6099. :return: None
  6100. """
  6101. self.log.debug("save_project()")
  6102. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6103. ## Capture the latest changes
  6104. # Current object
  6105. try:
  6106. self.collection.get_active().read_form()
  6107. except:
  6108. self.log.debug("There was no active object")
  6109. pass
  6110. # Project options
  6111. self.options_read_form()
  6112. # Serialize the whole project
  6113. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6114. "options": self.options,
  6115. "version": self.version}
  6116. if self.defaults["global_save_compressed"] is True:
  6117. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6118. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6119. # # Write
  6120. f.write(g)
  6121. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6122. else:
  6123. # Open file
  6124. try:
  6125. f = open(filename, 'w')
  6126. except IOError:
  6127. App.log.error("Failed to open file for saving: %s", filename)
  6128. return
  6129. # Write
  6130. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6131. f.close()
  6132. # verification of the saved project
  6133. # Open and parse
  6134. try:
  6135. saved_f = open(filename, 'r')
  6136. except IOError:
  6137. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6138. return
  6139. try:
  6140. saved_d = json.load(saved_f, object_hook=dict2obj)
  6141. except:
  6142. self.inform.emit(
  6143. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6144. f.close()
  6145. return
  6146. saved_f.close()
  6147. if 'version' in saved_d:
  6148. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6149. else:
  6150. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6151. def on_options_app2project(self):
  6152. """
  6153. Callback for Options->Transfer Options->App=>Project. Copies options
  6154. from application defaults to project defaults.
  6155. :return: None
  6156. """
  6157. self.report_usage("on_options_app2project")
  6158. self.defaults_read_form()
  6159. self.options.update(self.defaults)
  6160. self.options_write_form()
  6161. def on_options_project2app(self):
  6162. """
  6163. Callback for Options->Transfer Options->Project=>App. Copies options
  6164. from project defaults to application defaults.
  6165. :return: None
  6166. """
  6167. self.report_usage("on_options_project2app")
  6168. self.options_read_form()
  6169. self.defaults.update(self.options)
  6170. self.defaults_write_form()
  6171. def on_options_project2object(self):
  6172. """
  6173. Callback for Options->Transfer Options->Project=>Object. Copies options
  6174. from project defaults to the currently selected object.
  6175. :return: None
  6176. """
  6177. self.report_usage("on_options_project2object")
  6178. self.options_read_form()
  6179. obj = self.collection.get_active()
  6180. if obj is None:
  6181. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6182. return
  6183. for option in self.options:
  6184. if option.find(obj.kind + "_") == 0:
  6185. oname = option[len(obj.kind) + 1:]
  6186. obj.options[oname] = self.options[option]
  6187. obj.to_form() # Update UI
  6188. def on_options_object2project(self):
  6189. """
  6190. Callback for Options->Transfer Options->Object=>Project. Copies options
  6191. from the currently selected object to project defaults.
  6192. :return: None
  6193. """
  6194. self.report_usage("on_options_object2project")
  6195. obj = self.collection.get_active()
  6196. if obj is None:
  6197. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6198. return
  6199. obj.read_form()
  6200. for option in obj.options:
  6201. if option in ['name']: # TODO: Handle this better...
  6202. continue
  6203. self.options[obj.kind + "_" + option] = obj.options[option]
  6204. self.options_write_form()
  6205. def on_options_object2app(self):
  6206. """
  6207. Callback for Options->Transfer Options->Object=>App. Copies options
  6208. from the currently selected object to application defaults.
  6209. :return: None
  6210. """
  6211. self.report_usage("on_options_object2app")
  6212. obj = self.collection.get_active()
  6213. if obj is None:
  6214. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6215. return
  6216. obj.read_form()
  6217. for option in obj.options:
  6218. if option in ['name']: # TODO: Handle this better...
  6219. continue
  6220. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6221. self.defaults_write_form()
  6222. def on_options_app2object(self):
  6223. """
  6224. Callback for Options->Transfer Options->App=>Object. Copies options
  6225. from application defaults to the currently selected object.
  6226. :return: None
  6227. """
  6228. self.report_usage("on_options_app2object")
  6229. self.defaults_read_form()
  6230. obj = self.collection.get_active()
  6231. if obj is None:
  6232. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6233. return
  6234. for option in self.defaults:
  6235. if option.find(obj.kind + "_") == 0:
  6236. oname = option[len(obj.kind) + 1:]
  6237. obj.options[oname] = self.defaults[option]
  6238. obj.to_form() # Update UI
  6239. # end of file