FlatCAMApp.py 535 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915
  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
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool, cpu_count
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from flatcamEditors.FlatCAMTextEditor import TextEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. # from flatcamGUI.VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. import tclCommands
  50. import gettext
  51. import FlatCAMTranslation as fcTranslate
  52. import builtins
  53. if sys.platform == 'win32':
  54. import winreg
  55. fcTranslate.apply_language('strings')
  56. if '_' not in builtins.__dict__:
  57. _ = gettext.gettext
  58. class App(QtCore.QObject):
  59. # ########################################
  60. # # App ###
  61. # ########################################
  62. """
  63. The main application class. The constructor starts the GUI.
  64. """
  65. # Get Cmd Line Options
  66. cmd_line_shellfile = ''
  67. cmd_line_shellvar = ''
  68. cmd_line_headless = None
  69. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  70. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  71. "FlatCam.py --headless=1"
  72. try:
  73. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  74. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  75. "shellvar=",
  76. "headless=",
  77. "multiprocessing-fork="])
  78. except getopt.GetoptError:
  79. print(cmd_line_help)
  80. sys.exit(2)
  81. for opt, arg in cmd_line_options:
  82. if opt == '-h':
  83. print(cmd_line_help)
  84. sys.exit()
  85. elif opt == '--shellfile':
  86. cmd_line_shellfile = arg
  87. elif opt == '--shellvar':
  88. cmd_line_shellvar = arg
  89. elif opt == '--headless':
  90. try:
  91. cmd_line_headless = eval(arg)
  92. except NameError:
  93. pass
  94. # ## Logging ###
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ##########################################################################
  103. # ################## Version and VERSION DATE ##############################
  104. # ##########################################################################
  105. version = 8.98
  106. version_date = "2019/10/7"
  107. beta = True
  108. engine = '3D'
  109. # current date now
  110. date = str(datetime.today()).rpartition('.')[0]
  111. date = ''.join(c for c in date if c not in ':-')
  112. date = date.replace(' ', '_')
  113. # URL for update checks and statistics
  114. version_url = "http://flatcam.org/version"
  115. # App URL
  116. app_url = "http://flatcam.org"
  117. # Manual URL
  118. manual_url = "http://flatcam.org/manual/index.html"
  119. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  120. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  121. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  122. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  123. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  124. # this variable will hold the project status
  125. # if True it will mean that the project was modified and not saved
  126. should_we_save = False
  127. # flag is True if saving action has been triggered
  128. save_in_progress = False
  129. # ###########################################################################
  130. # ############################# Signals ################################
  131. # ###########################################################################
  132. # Inform the user
  133. # Handled by:
  134. # * App.info() --> Print on the status bar
  135. inform = QtCore.pyqtSignal(str)
  136. app_quit = QtCore.pyqtSignal()
  137. # General purpose background task
  138. worker_task = QtCore.pyqtSignal(dict)
  139. # File opened
  140. # Handled by:
  141. # * register_folder()
  142. # * register_recent()
  143. # Note: Setting the parameters to unicode does not seem
  144. # to have an effect. Then are received as Qstring
  145. # anyway.
  146. # File type and filename
  147. file_opened = QtCore.pyqtSignal(str, str)
  148. # File type and filename
  149. file_saved = QtCore.pyqtSignal(str, str)
  150. # Percentage of progress
  151. progress = QtCore.pyqtSignal(int)
  152. plots_updated = QtCore.pyqtSignal()
  153. # Emitted by new_object() and passes the new object as argument, plot flag.
  154. # on_object_created() adds the object to the collection, plots on appropriate flag
  155. # and emits new_object_available.
  156. object_created = QtCore.pyqtSignal(object, bool, bool)
  157. # Emitted when a object has been changed (like scaled, mirrored)
  158. object_changed = QtCore.pyqtSignal(object)
  159. # Emitted after object has been plotted.
  160. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  161. object_plotted = QtCore.pyqtSignal(object)
  162. # Emitted when a new object has been added or deleted from/to the collection
  163. object_status_changed = QtCore.pyqtSignal(object, str, str)
  164. message = QtCore.pyqtSignal(str, str, str)
  165. # Emmited when shell command is finished(one command only)
  166. shell_command_finished = QtCore.pyqtSignal(object)
  167. # Emitted when multiprocess pool has been recreated
  168. pool_recreated = QtCore.pyqtSignal(object)
  169. # Emitted when an unhandled exception happens
  170. # in the worker task.
  171. thread_exception = QtCore.pyqtSignal(object)
  172. # used to signal that there are arguments for the app
  173. args_at_startup = QtCore.pyqtSignal(list)
  174. # a reusable signal to replot a list of objects
  175. # should be disconnected after use so it can be reused
  176. replot_signal = pyqtSignal(list)
  177. def __init__(self, user_defaults=True, post_gui=None):
  178. """
  179. Starts the application.
  180. :return: app
  181. :rtype: App
  182. """
  183. App.log.info("FlatCAM Starting...")
  184. self.main_thread = QtWidgets.QApplication.instance().thread()
  185. # ############################################################################
  186. # # ################# OS-specific ############################################
  187. # ############################################################################
  188. portable = False
  189. # Folder for user settings.
  190. if sys.platform == 'win32':
  191. # #########################################################################
  192. # Setup the listening thread for another instance launching with args #####
  193. # #########################################################################
  194. # make sure the thread is stored by using a self. otherwise it's garbage collected
  195. self.th = QtCore.QThread()
  196. self.th.start(priority=QtCore.QThread.LowestPriority)
  197. self.new_launch = ArgsThread()
  198. self.new_launch.open_signal[list].connect(self.on_startup_args)
  199. self.new_launch.moveToThread(self.th)
  200. self.new_launch.start.emit()
  201. from win32com.shell import shell, shellcon
  202. if platform.architecture()[0] == '32bit':
  203. App.log.debug("Win32!")
  204. else:
  205. App.log.debug("Win64!")
  206. # #########################################################################
  207. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  208. # #########################################################################
  209. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  210. try:
  211. with open(config_file, 'r'):
  212. pass
  213. except FileNotFoundError:
  214. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  215. try:
  216. with open(config_file, 'r') as f:
  217. try:
  218. for line in f:
  219. param = str(line).replace('\n', '').rpartition('=')
  220. if param[0] == 'portable':
  221. try:
  222. portable = eval(param[2])
  223. except NameError:
  224. portable = False
  225. if param[0] == 'headless':
  226. if param[2].lower() == 'true':
  227. self.cmd_line_headless = 1
  228. else:
  229. self.cmd_line_headless = None
  230. except Exception as e:
  231. log.debug('App.__init__() -->%s' % str(e))
  232. return
  233. except FileNotFoundError as e:
  234. log.debug(str(e))
  235. pass
  236. if portable is False:
  237. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  238. else:
  239. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  240. self.os = 'windows'
  241. else: # Linux/Unix/MacOS
  242. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  243. self.os = 'unix'
  244. # ##########################################################################
  245. # ################## Setup folders and files ###############################
  246. # ##########################################################################
  247. if not os.path.exists(self.data_path):
  248. os.makedirs(self.data_path)
  249. App.log.debug('Created data folder: ' + self.data_path)
  250. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  251. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  252. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  253. if not os.path.exists(self.postprocessorpaths):
  254. os.makedirs(self.postprocessorpaths)
  255. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  256. # create current_defaults.FlatConfig file if there is none
  257. try:
  258. f = open(self.data_path + '/current_defaults.FlatConfig')
  259. f.close()
  260. except IOError:
  261. App.log.debug('Creating empty current_defaults.FlatConfig')
  262. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  263. json.dump({}, f)
  264. f.close()
  265. # create factory_defaults.FlatConfig file if there is none
  266. try:
  267. f = open(self.data_path + '/factory_defaults.FlatConfig')
  268. f.close()
  269. except IOError:
  270. App.log.debug('Creating empty factory_defaults.FlatConfig')
  271. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  272. json.dump({}, f)
  273. f.close()
  274. # create a recent files json file if there is none
  275. try:
  276. f = open(self.data_path + '/recent.json')
  277. f.close()
  278. except IOError:
  279. App.log.debug('Creating empty recent.json')
  280. f = open(self.data_path + '/recent.json', 'w')
  281. json.dump([], f)
  282. f.close()
  283. # create a recent projects json file if there is none
  284. try:
  285. fp = open(self.data_path + '/recent_projects.json')
  286. fp.close()
  287. except IOError:
  288. App.log.debug('Creating empty recent_projects.json')
  289. fp = open(self.data_path + '/recent_projects.json', 'w')
  290. json.dump([], fp)
  291. fp.close()
  292. # Application directory. CHDIR to it. Otherwise, trying to load
  293. # GUI icons will fail as their path is relative.
  294. # This will fail under cx_freeze ...
  295. self.app_home = os.path.dirname(os.path.realpath(__file__))
  296. App.log.debug("Application path is " + self.app_home)
  297. App.log.debug("Started in " + os.getcwd())
  298. # cx_freeze workaround
  299. if os.path.isfile(self.app_home):
  300. self.app_home = os.path.dirname(self.app_home)
  301. os.chdir(self.app_home)
  302. # #############################################################################
  303. # ##################### CREATE MULTIPROCESSING POOL ###########################
  304. # #############################################################################
  305. self.pool = Pool(processes=cpu_count())
  306. # ##########################################################################
  307. # ################## Setting the Splash Screen #############################
  308. # ##########################################################################
  309. settings = QSettings("Open Source", "FlatCAM")
  310. if settings.contains("splash_screen"):
  311. show_splash = settings.value("splash_screen")
  312. else:
  313. settings.setValue('splash_screen', 1)
  314. # This will write the setting to the platform specific storage.
  315. del settings
  316. show_splash = 1
  317. if show_splash and self.cmd_line_headless != 1:
  318. splash_pix = QtGui.QPixmap('share/splash.png')
  319. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  320. # self.splash.setMask(splash_pix.mask())
  321. # move splashscreen to the current monitor
  322. desktop = QtWidgets.QApplication.desktop()
  323. screen = desktop.screenNumber(QtGui.QCursor.pos())
  324. current_screen_center = desktop.availableGeometry(screen).center()
  325. self.splash.move(current_screen_center - self.splash.rect().center())
  326. self.splash.show()
  327. self.splash.showMessage(_("FlatCAM is initializing ..."),
  328. alignment=Qt.AlignBottom | Qt.AlignLeft,
  329. color=QtGui.QColor("gray"))
  330. else:
  331. show_splash = 0
  332. # #############################################################################
  333. # ##################### Initialize GUI ########################################
  334. # #############################################################################
  335. # FlatCAM colors used in plotting
  336. self.FC_light_green = '#BBF268BF'
  337. self.FC_dark_green = '#006E20BF'
  338. self.FC_light_blue = '#a5a5ffbf'
  339. self.FC_dark_blue = '#0000ffbf'
  340. QtCore.QObject.__init__(self)
  341. self.ui = FlatCAMGUI(self.version, self.beta, self)
  342. settings = QtCore.QSettings("Open Source", "FlatCAM")
  343. if settings.contains("theme"):
  344. theme = settings.value('theme', type=str)
  345. else:
  346. theme = 'white'
  347. if theme == 'white':
  348. self.cursor_color_3D = 'black'
  349. else:
  350. self.cursor_color_3D = 'gray'
  351. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  352. self.ui.final_save.connect(self.final_save)
  353. # #############################################################################
  354. # ############################## Data #########################################
  355. # #############################################################################
  356. self.recent = []
  357. self.recent_projects = []
  358. self.clipboard = QtWidgets.QApplication.clipboard()
  359. self.project_filename = None
  360. self.toggle_units_ignore = False
  361. # self.defaults_form = PreferencesUI()
  362. # when adding entries here read the comments in the method found bellow named:
  363. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  364. self.defaults_form_fields = {
  365. # General App
  366. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  367. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  368. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  369. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  370. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  371. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  372. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  373. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  374. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  375. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  376. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  377. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  378. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  379. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  380. # General GUI Preferences
  381. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  382. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  383. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  384. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  385. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  386. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  387. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  388. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  389. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  390. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  391. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  392. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  393. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  394. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  395. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  396. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  397. # General GUI Settings
  398. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  399. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  400. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  401. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  402. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  403. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  404. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  405. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  406. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  407. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  408. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  409. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  410. # Gerber General
  411. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  412. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  413. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  414. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  415. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  416. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  417. # Gerber Options
  418. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  419. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  420. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  421. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  422. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  423. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  424. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  425. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  426. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  427. # Gerber Advanced Options
  428. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  429. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  430. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  431. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  432. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  433. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  434. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  435. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  436. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  437. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  438. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  439. # Gerber Export
  440. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  441. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  442. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  443. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  444. # Gerber Editor
  445. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  446. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  447. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  448. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  449. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  450. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  451. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  452. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  453. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  454. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  455. "gerber_editor_circ_angle":
  456. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  457. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  458. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  459. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  460. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  461. # Excellon General
  462. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  463. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  464. "excellon_format_upper_in":
  465. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  466. "excellon_format_lower_in":
  467. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  468. "excellon_format_upper_mm":
  469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  470. "excellon_format_lower_mm":
  471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  472. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  473. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  474. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  475. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  476. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  477. # Excellon Options
  478. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  479. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  480. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  481. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  482. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  483. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  484. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  485. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  486. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  487. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  488. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  489. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  490. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  491. # Excellon Advanced Options
  492. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  493. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  494. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  495. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  496. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  497. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  498. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  499. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  500. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  501. # Excellon Export
  502. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  503. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  504. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  505. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  506. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  507. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  508. # Excellon Editor
  509. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  510. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  511. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  512. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  513. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  514. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  515. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  516. "excellon_editor_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  518. # Excellon Slots
  519. "excellon_editor_slot_direction":
  520. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  521. "excellon_editor_slot_angle":
  522. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  523. "excellon_editor_slot_length":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  525. # Excellon Slots
  526. "excellon_editor_slot_array_size":
  527. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  528. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  529. "excellon_editor_slot_lin_pitch":
  530. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  531. "excellon_editor_slot_lin_angle":
  532. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  533. "excellon_editor_slot_circ_dir":
  534. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  535. "excellon_editor_slot_circ_angle":
  536. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  537. # Geometry General
  538. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  539. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  540. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  541. # Geometry Options
  542. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  543. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  544. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  545. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  546. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  547. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  548. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  549. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  550. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  551. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  552. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  553. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  554. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  555. # Geometry Advanced Options
  556. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  557. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  558. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  559. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  560. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  561. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  562. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  563. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  564. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  565. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  566. # Geometry Editor
  567. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  568. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  569. # CNCJob General
  570. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  571. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  572. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  573. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  574. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  575. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  576. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  577. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  578. # CNC Job Options
  579. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  580. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  581. # CNC Job Advanced Options
  582. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  583. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  584. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  585. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  586. # NCC Tool
  587. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  588. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  589. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  590. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  591. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  592. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  593. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  594. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  595. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  596. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  597. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  598. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  599. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  600. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  601. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  602. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  603. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  604. # CutOut Tool
  605. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  606. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  607. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  608. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  609. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  610. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  611. # Paint Area Tool
  612. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  613. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  614. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  615. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  616. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  617. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  618. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  619. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  620. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  621. # 2-sided Tool
  622. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  623. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  624. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  625. # Film Tool
  626. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  627. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  628. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  629. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  630. # Panelize Tool
  631. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  632. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  633. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  634. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  635. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  636. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  637. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  638. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  639. # Calculators Tool
  640. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  641. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  642. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  643. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  644. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  645. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  646. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  647. # Transformations Tool
  648. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  649. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  650. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  651. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  652. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  653. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  654. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  655. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  656. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  657. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  658. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  659. # SolderPaste Dispensing Tool
  660. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  661. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  662. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  663. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  664. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  665. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  666. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  667. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  668. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  669. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  670. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  671. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  672. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  673. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  674. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  675. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  676. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  677. # Utilities
  678. # File associations
  679. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  680. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  681. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  682. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  683. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  684. }
  685. # ############################
  686. # ### LOAD POSTPROCESSORS ####
  687. # ############################
  688. self.postprocessors = load_postprocessors(self)
  689. for name in list(self.postprocessors.keys()):
  690. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  691. if name.partition('_')[0] == 'Paste':
  692. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  693. continue
  694. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  695. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  696. if name == 'hpgl':
  697. continue
  698. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  699. # ############################
  700. # ### LOAD LANGUAGES ####
  701. # ############################
  702. self.languages = fcTranslate.load_languages()
  703. for name in sorted(self.languages.values()):
  704. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  705. # #################################################################################
  706. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  707. # #################################################################################
  708. self.defaults = LoudDict()
  709. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  710. self.defaults.update({
  711. # Global APP Preferences
  712. "first_run": True,
  713. "units": "IN",
  714. "global_serial": 0,
  715. "global_stats": {},
  716. "global_tabs_detachable": True,
  717. "global_graphic_engine": '3D',
  718. "global_app_level": 'b',
  719. "global_portable": False,
  720. "global_language": 'English',
  721. "global_version_check": True,
  722. "global_send_stats": True,
  723. "global_pan_button": '2',
  724. "global_mselect_key": 'Control',
  725. "global_project_at_startup": False,
  726. "global_systray_icon": True,
  727. "global_project_autohide": True,
  728. "global_toggle_tooltips": True,
  729. "global_worker_number": 2,
  730. "global_tolerance": 0.0002,
  731. "global_open_style": True,
  732. "global_delete_confirmation": True,
  733. "global_compression_level": 3,
  734. "global_save_compressed": True,
  735. # Global GUI Preferences
  736. "global_gridx": 0.0393701,
  737. "global_gridy": 0.0393701,
  738. "global_snap_max": 0.001968504,
  739. "global_workspace": False,
  740. "global_workspaceT": "A4P",
  741. "global_grid_context_menu": {
  742. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  743. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  744. },
  745. "global_plot_fill": '#BBF268BF',
  746. "global_plot_line": '#006E20BF',
  747. "global_sel_fill": '#a5a5ffbf',
  748. "global_sel_line": '#0000ffbf',
  749. "global_alt_sel_fill": '#BBF268BF',
  750. "global_alt_sel_line": '#006E20BF',
  751. "global_draw_color": '#FF0000',
  752. "global_sel_draw_color": '#0000FF',
  753. "global_proj_item_color": '#000000',
  754. "global_proj_item_dis_color": '#b7b7cb',
  755. "global_activity_icon": 'Ball green',
  756. "global_toolbar_view": 511,
  757. "global_background_timeout": 300000, # Default value is 5 minutes
  758. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  759. # (python trace only for unknown errors),
  760. # 1 = show trace(show trace always),
  761. # 2 = (For the future).
  762. # Persistence
  763. "global_last_folder": None,
  764. "global_last_save_folder": None,
  765. # Default window geometry
  766. "global_def_win_x": 100,
  767. "global_def_win_y": 100,
  768. "global_def_win_w": 1024,
  769. "global_def_win_h": 650,
  770. "global_def_notebook_width": 1,
  771. # Constants...
  772. "global_defaults_save_period_ms": 20000, # Time between default saves.
  773. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  774. "global_shell_at_startup": False, # Show the shell at startup.
  775. "global_recent_limit": 10, # Max. items in recent list.
  776. "fit_key": 'V',
  777. "zoom_out_key": '-',
  778. "zoom_in_key": '=',
  779. "grid_toggle_key": 'G',
  780. "global_zoom_ratio": 1.5,
  781. "global_point_clipboard_format": "(%.4f, %.4f)",
  782. "global_zdownrate": None,
  783. # General GUI Settings
  784. "global_theme": 'white',
  785. "global_hover": False,
  786. "global_selection_shape": True,
  787. "global_layout": "compact",
  788. "global_cursor_type": "small",
  789. "global_cursor_size": 20,
  790. # Gerber General
  791. "gerber_plot": True,
  792. "gerber_solid": True,
  793. "gerber_multicolored": False,
  794. "gerber_circle_steps": 128,
  795. "gerber_use_buffer_for_union": True,
  796. "gerber_def_units": 'IN',
  797. "gerber_def_zeros": 'L',
  798. # Gerber Options
  799. "gerber_isotooldia": 0.00787402,
  800. "gerber_isopasses": 1,
  801. "gerber_isooverlap": 0.00393701,
  802. "gerber_milling_type": "cl",
  803. "gerber_combine_passes": False,
  804. "gerber_noncoppermargin": 0.00393701,
  805. "gerber_noncopperrounded": False,
  806. "gerber_bboxmargin": 0.00393701,
  807. "gerber_bboxrounded": False,
  808. # Gerber Advanced Options
  809. "gerber_aperture_display": False,
  810. "gerber_aperture_scale_factor": 1.0,
  811. "gerber_aperture_buffer_factor": 0.0,
  812. "gerber_follow": False,
  813. "gerber_tool_type": 'circular',
  814. "gerber_vtipdia": 0.1,
  815. "gerber_vtipangle": 30,
  816. "gerber_vcutz": -0.05,
  817. "gerber_buffering": "full",
  818. "gerber_simplification": False,
  819. "gerber_simp_tolerance": 0.0005,
  820. # Gerber Export
  821. "gerber_exp_units": 'IN',
  822. "gerber_exp_integer": 2,
  823. "gerber_exp_decimals": 4,
  824. "gerber_exp_zeros": 'L',
  825. # Gerber Editor
  826. "gerber_editor_sel_limit": 30,
  827. "gerber_editor_newcode": 10,
  828. "gerber_editor_newsize": 0.8,
  829. "gerber_editor_newtype": 'C',
  830. "gerber_editor_newdim": "0.5, 0.5",
  831. "gerber_editor_array_size": 5,
  832. "gerber_editor_lin_axis": 'X',
  833. "gerber_editor_lin_pitch": 1,
  834. "gerber_editor_lin_angle": 0.0,
  835. "gerber_editor_circ_dir": 'CW',
  836. "gerber_editor_circ_angle": 0.0,
  837. "gerber_editor_scale_f": 1.0,
  838. "gerber_editor_buff_f": 0.1,
  839. "gerber_editor_ma_low": 0.0,
  840. "gerber_editor_ma_high": 1.0,
  841. # Excellon General
  842. "excellon_plot": True,
  843. "excellon_solid": True,
  844. "excellon_format_upper_in": 2,
  845. "excellon_format_lower_in": 4,
  846. "excellon_format_upper_mm": 3,
  847. "excellon_format_lower_mm": 3,
  848. "excellon_zeros": "L",
  849. "excellon_units": "INCH",
  850. "excellon_update": True,
  851. "excellon_optimization_type": 'B',
  852. "excellon_search_time": 3,
  853. # Excellon Options
  854. "excellon_drillz": -0.0590551,
  855. "excellon_travelz": 0.0787402,
  856. "excellon_endz": 0.5,
  857. "excellon_feedrate": 3.14961,
  858. "excellon_spindlespeed": None,
  859. "excellon_dwell": False,
  860. "excellon_dwelltime": 1,
  861. "excellon_toolchange": False,
  862. "excellon_toolchangez": 0.5,
  863. "excellon_ppname_e": 'default',
  864. "excellon_tooldia": 0.0314961,
  865. "excellon_slot_tooldia": 0.0708661,
  866. "excellon_gcode_type": "drills",
  867. # Excellon Advanced Options
  868. "excellon_offset": 0.0,
  869. "excellon_toolchangexy": "0.0, 0.0",
  870. "excellon_startz": None,
  871. "excellon_feedrate_rapid": 31.4961,
  872. "excellon_z_pdepth": -0.02,
  873. "excellon_feedrate_probe": 3.14961,
  874. "excellon_spindledir": 'CW',
  875. "excellon_f_plunge": False,
  876. "excellon_f_retract": False,
  877. # Excellon Export
  878. "excellon_exp_units": 'INCH',
  879. "excellon_exp_format": 'ndec',
  880. "excellon_exp_integer": 2,
  881. "excellon_exp_decimals": 4,
  882. "excellon_exp_zeros": 'LZ',
  883. "excellon_exp_slot_type": 'routing',
  884. # Excellon Editor
  885. "excellon_editor_sel_limit": 30,
  886. "excellon_editor_newdia": 0.039,
  887. "excellon_editor_array_size": 5,
  888. "excellon_editor_lin_dir": 'X',
  889. "excellon_editor_lin_pitch": 0.1,
  890. "excellon_editor_lin_angle": 0.0,
  891. "excellon_editor_circ_dir": 'CW',
  892. "excellon_editor_circ_angle": 12,
  893. # Excellon Slots
  894. "excellon_editor_slot_direction": 'X',
  895. "excellon_editor_slot_angle": 0.0,
  896. "excellon_editor_slot_length": 5.0,
  897. # Excellon Slot Array
  898. "excellon_editor_slot_array_size": 5,
  899. "excellon_editor_slot_lin_dir": 'X',
  900. "excellon_editor_slot_lin_pitch": 0.1,
  901. "excellon_editor_slot_lin_angle": 0.0,
  902. "excellon_editor_slot_circ_dir": 'CW',
  903. "excellon_editor_slot_circ_angle": 0.0,
  904. # Geometry General
  905. "geometry_plot": True,
  906. "geometry_circle_steps": 128,
  907. "geometry_cnctooldia": "0.0944882",
  908. # Geometry Options
  909. "geometry_cutz": -0.0944882,
  910. "geometry_vtipdia": 0.1,
  911. "geometry_vtipangle": 30,
  912. "geometry_multidepth": False,
  913. "geometry_depthperpass": 0.0314961,
  914. "geometry_travelz": 0.0787402,
  915. "geometry_toolchange": False,
  916. "geometry_toolchangez": 0.5,
  917. "geometry_endz": 0.5,
  918. "geometry_feedrate": 3.14961,
  919. "geometry_feedrate_z": 3.14961,
  920. "geometry_spindlespeed": None,
  921. "geometry_dwell": False,
  922. "geometry_dwelltime": 1,
  923. "geometry_ppname_g": 'default',
  924. # Geometry Advanced Options
  925. "geometry_toolchangexy": "0.0, 0.0",
  926. "geometry_startz": None,
  927. "geometry_feedrate_rapid": 3.14961,
  928. "geometry_extracut": False,
  929. "geometry_z_pdepth": -0.02,
  930. "geometry_f_plunge": False,
  931. "geometry_spindledir": 'CW',
  932. "geometry_feedrate_probe": 3.14961,
  933. "geometry_segx": 0.0,
  934. "geometry_segy": 0.0,
  935. # Geometry Editor
  936. "geometry_editor_sel_limit": 30,
  937. "geometry_editor_milling_type": "cl",
  938. # CNC Job General
  939. "cncjob_plot": True,
  940. "cncjob_plot_kind": 'all',
  941. "cncjob_annotation": True,
  942. "cncjob_tooldia": 0.0393701,
  943. "cncjob_coords_type": "G90",
  944. "cncjob_coords_decimals": 4,
  945. "cncjob_fr_decimals": 2,
  946. "cncjob_steps_per_circle": 128,
  947. # CNC Job Options
  948. "cncjob_prepend": "",
  949. "cncjob_append": "",
  950. # CNC Job Advanced Options
  951. "cncjob_toolchange_macro": "",
  952. "cncjob_toolchange_macro_enable": False,
  953. "cncjob_annotation_fontsize": 9,
  954. "cncjob_annotation_fontcolor": '#990000',
  955. # NCC Tool
  956. "tools_ncctools": "0.0393701, 0.019685",
  957. "tools_nccorder": 'rev',
  958. "tools_nccoverlap": 0.015748,
  959. "tools_nccmargin": 0.0393701,
  960. "tools_nccmethod": "seed",
  961. "tools_nccconnect": True,
  962. "tools_ncccontour": True,
  963. "tools_nccrest": False,
  964. "tools_ncc_offset_choice": False,
  965. "tools_ncc_offset_value": 0.0000,
  966. "tools_nccref": 'itself',
  967. "tools_ncc_plotting": 'normal',
  968. "tools_nccmilling_type": 'cl',
  969. "tools_ncctool_type": 'V',
  970. "tools_ncccutz": -0.001968504,
  971. "tools_ncctipdia": 0.00393701,
  972. "tools_ncctipangle": 30,
  973. # Cutout Tool
  974. "tools_cutouttooldia": 0.0944882,
  975. "tools_cutoutkind": "single",
  976. "tools_cutoutmargin": 0.00393701,
  977. "tools_cutoutgapsize": 0.15748,
  978. "tools_gaps_ff": "4",
  979. "tools_cutout_convexshape": False,
  980. # Paint Tool
  981. "tools_painttooldia": 0.023622,
  982. "tools_paintorder": 'rev',
  983. "tools_paintoverlap": 0.015748,
  984. "tools_paintmargin": 0.0,
  985. "tools_paintmethod": "seed",
  986. "tools_selectmethod": "all",
  987. "tools_pathconnect": True,
  988. "tools_paintcontour": True,
  989. "tools_paint_plotting": 'normal',
  990. # 2-Sided Tool
  991. "tools_2sided_mirror_axis": "X",
  992. "tools_2sided_axis_loc": "point",
  993. "tools_2sided_drilldia": 0.11811,
  994. # Film Tool
  995. "tools_film_type": 'neg',
  996. "tools_film_boundary": 0.0393701,
  997. "tools_film_scale": 0,
  998. "tools_film_color": '#000000',
  999. # Panel Tool
  1000. "tools_panelize_spacing_columns": 0,
  1001. "tools_panelize_spacing_rows": 0,
  1002. "tools_panelize_columns": 1,
  1003. "tools_panelize_rows": 1,
  1004. "tools_panelize_constrain": False,
  1005. "tools_panelize_constrainx": 0.0,
  1006. "tools_panelize_constrainy": 0.0,
  1007. "tools_panelize_panel_type": 'gerber',
  1008. # Calculators Tool
  1009. "tools_calc_vshape_tip_dia": 0.007874,
  1010. "tools_calc_vshape_tip_angle": 30,
  1011. "tools_calc_vshape_cut_z": 0.000787,
  1012. "tools_calc_electro_length": 10.0,
  1013. "tools_calc_electro_width": 10.0,
  1014. "tools_calc_electro_cdensity": 13.0,
  1015. "tools_calc_electro_growth": 10.0,
  1016. # Transform Tool
  1017. "tools_transform_rotate": 90,
  1018. "tools_transform_skew_x": 0.0,
  1019. "tools_transform_skew_y": 0.0,
  1020. "tools_transform_scale_x": 1.0,
  1021. "tools_transform_scale_y": 1.0,
  1022. "tools_transform_scale_link": True,
  1023. "tools_transform_scale_reference": True,
  1024. "tools_transform_offset_x": 0.0,
  1025. "tools_transform_offset_y": 0.0,
  1026. "tools_transform_mirror_reference": False,
  1027. "tools_transform_mirror_point": (0, 0),
  1028. # SolderPaste Tool
  1029. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1030. "tools_solderpaste_new": 0.011811,
  1031. "tools_solderpaste_z_start": 0.00019685039,
  1032. "tools_solderpaste_z_dispense": 0.00393701,
  1033. "tools_solderpaste_z_stop": 0.00019685039,
  1034. "tools_solderpaste_z_travel": 0.00393701,
  1035. "tools_solderpaste_z_toolchange": 0.0393701,
  1036. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1037. "tools_solderpaste_frxy": 3.0,
  1038. "tools_solderpaste_frz": 3.0,
  1039. "tools_solderpaste_frz_dispense": 0.0393701,
  1040. "tools_solderpaste_speedfwd": 20,
  1041. "tools_solderpaste_dwellfwd": 1,
  1042. "tools_solderpaste_speedrev": 10,
  1043. "tools_solderpaste_dwellrev": 1,
  1044. "tools_solderpaste_pp": 'Paste_1',
  1045. # Subtract Tool
  1046. "tools_sub_close_paths": True,
  1047. # Utilities
  1048. # file associations
  1049. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1050. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1051. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1052. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1053. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1054. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1055. # Keyword list
  1056. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1057. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1058. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1059. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1060. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1061. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1062. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1063. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1064. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1065. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1066. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move',
  1067. "script_autocompleter": True,
  1068. "script_text": "",
  1069. "script_plot": True,
  1070. "script_source_file": "",
  1071. "document_autocompleter": False,
  1072. "document_text": "",
  1073. "document_plot": True,
  1074. "document_source_file": "",
  1075. "document_font_color": '#000000',
  1076. "document_sel_color": '#0055ff',
  1077. "document_font_size": 6,
  1078. "document_tab_size": 80,
  1079. })
  1080. # ############################################################
  1081. # ############### Load defaults from file ####################
  1082. # ############################################################
  1083. if user_defaults:
  1084. self.load_defaults(filename='current_defaults')
  1085. # #############################################################
  1086. # ############## APPLY APP LANGUAGE ###########################
  1087. # #############################################################
  1088. ret_val = fcTranslate.apply_language('strings')
  1089. if ret_val == "no language":
  1090. self.inform.emit('[ERROR] %s' %
  1091. _("Could not find the Language files. The App strings are missing."))
  1092. log.debug("Could not find the Language files. The App strings are missing.")
  1093. else:
  1094. # make the current language the current selection on the language combobox
  1095. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1096. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1097. # ##############################################################
  1098. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1099. # ##############################################################
  1100. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1101. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1102. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1103. self.save_defaults(silent=True, first_time=True)
  1104. self.propagate_defaults(silent=True)
  1105. self.restore_main_win_geom()
  1106. # def auto_save_defaults():
  1107. # try:
  1108. # self.save_defaults(silent=True)
  1109. # self.propagate_defaults(silent=True)
  1110. # finally:
  1111. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1112. # the following lines activates automatic defaults save
  1113. # if user_defaults:
  1114. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1115. # self.options_form = PreferencesUI()
  1116. self.options_form_fields = {
  1117. "units": self.ui.general_options_form.general_app_group.units_radio,
  1118. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1119. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1120. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1121. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1122. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1123. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1124. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1125. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1126. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1127. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1128. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1129. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1130. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1131. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1132. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1133. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1134. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1135. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1136. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1137. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1138. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1139. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1140. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1141. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1142. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1143. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1144. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1145. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1146. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1147. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1148. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1149. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1150. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1151. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1152. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1153. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1154. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1155. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1156. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1157. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1158. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1159. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1160. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1161. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1162. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1163. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1164. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1165. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1166. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1167. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1168. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1169. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1170. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1171. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1172. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1173. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1174. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1175. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1176. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1177. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1178. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1179. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1180. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1181. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1182. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1183. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1184. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1185. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1186. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1187. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1188. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1189. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1190. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1191. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1192. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1193. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1194. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1195. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1196. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1197. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1198. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1199. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1200. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1201. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1202. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1203. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1204. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1205. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1206. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1207. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1208. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1209. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1210. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1211. }
  1212. for name in list(self.postprocessors.keys()):
  1213. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1214. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1215. self.options = LoudDict()
  1216. self.options.set_change_callback(self.on_options_dict_change)
  1217. self.options.update({
  1218. "units": "IN",
  1219. "global_gridx": 1.0,
  1220. "global_gridy": 1.0,
  1221. "global_snap_max": 0.05,
  1222. "global_background_timeout": 300000, # Default value is 5 minutes
  1223. "global_verbose_error_level": 0, # Shell verbosity:
  1224. # 0 = default(python trace only for unknown errors),
  1225. # 1 = show trace(show trace allways), 2 = (For the future).
  1226. "gerber_plot": True,
  1227. "gerber_solid": True,
  1228. "gerber_multicolored": False,
  1229. "gerber_isotooldia": 0.016,
  1230. "gerber_isopasses": 1,
  1231. "gerber_isooverlap": 0.15,
  1232. "gerber_combine_passes": True,
  1233. "gerber_noncoppermargin": 0.0,
  1234. "gerber_noncopperrounded": False,
  1235. "gerber_bboxmargin": 0.0,
  1236. "gerber_bboxrounded": False,
  1237. "excellon_plot": True,
  1238. "excellon_solid": False,
  1239. "excellon_format_upper_in": 2,
  1240. "excellon_format_lower_in": 4,
  1241. "excellon_format_upper_mm": 3,
  1242. "excellon_format_lower_mm": 3,
  1243. "excellon_units": 'INCH',
  1244. "excellon_optimization_type": 'B',
  1245. "excellon_search_time": 3,
  1246. "excellon_zeros": "L",
  1247. "excellon_drillz": -0.1,
  1248. "excellon_travelz": 0.1,
  1249. "excellon_feedrate": 3.0,
  1250. "excellon_feedrate_rapid": 3.0,
  1251. "excellon_spindlespeed": None,
  1252. "excellon_spindledir": 'CW',
  1253. "excellon_dwell": True,
  1254. "excellon_dwelltime": 1000,
  1255. "excellon_toolchange": False,
  1256. "excellon_toolchangez": 1.0,
  1257. "excellon_toolchangexy": "0.0, 0.0",
  1258. "excellon_tooldia": 0.016,
  1259. "excellon_ppname_e": 'default',
  1260. "excellon_f_plunge": False,
  1261. "excellon_startz": None,
  1262. "excellon_endz": 2.0,
  1263. "geometry_plot": True,
  1264. "geometry_segx": 0.0,
  1265. "geometry_segy": 0.0,
  1266. "geometry_cutz": -0.002,
  1267. "geometry_vtipdia": 0.1,
  1268. "geometry_vtipangle": 30,
  1269. "geometry_travelz": 0.1,
  1270. "geometry_feedrate": 3.0,
  1271. "geometry_feedrate_z": 3.0,
  1272. "geometry_feedrate_rapid": 3.0,
  1273. "geometry_spindlespeed": None,
  1274. "geometry_spindledir": 'CW',
  1275. "geometry_dwell": True,
  1276. "geometry_dwelltime": 1000,
  1277. "geometry_cnctooldia": 0.016,
  1278. "geometry_toolchange": False,
  1279. "geometry_toolchangez": 2.0,
  1280. "geometry_toolchangexy": "0.0, 0.0",
  1281. "geometry_startz": None,
  1282. "geometry_endz": 2.0,
  1283. "geometry_ppname_g": "default",
  1284. "geometry_f_plunge": False,
  1285. "geometry_depthperpass": 0.002,
  1286. "geometry_multidepth": False,
  1287. "geometry_extracut": False,
  1288. "cncjob_plot": True,
  1289. "cncjob_tooldia": 0.016,
  1290. "cncjob_prepend": "",
  1291. "cncjob_append": "",
  1292. "tools_ncctools": "1.0, 0.5",
  1293. "tools_nccoverlap": 0.4,
  1294. "tools_nccmargin": 1,
  1295. "tools_cutouttooldia": 0.07,
  1296. "tools_cutoutmargin": 0.1,
  1297. "tools_cutoutgapsize": 0.15,
  1298. "tools_gaps_ff": "8",
  1299. "tools_painttooldia": 0.07,
  1300. "tools_paintoverlap": 0.15,
  1301. "tools_paintmargin": 0.0,
  1302. "tools_paintmethod": "seed",
  1303. "tools_selectmethod": "single",
  1304. "tools_pathconnect": True,
  1305. "tools_paintcontour": True,
  1306. "tools_2sided_mirror_axis": "X",
  1307. "tools_2sided_axis_loc": 'point',
  1308. "tools_2sided_drilldia": 1,
  1309. "tools_film_type": 'neg',
  1310. "tools_film_boundary": 1,
  1311. "tools_film_scale": 0,
  1312. "tools_panelize_spacing_columns": 0,
  1313. "tools_panelize_spacing_rows": 0,
  1314. "tools_panelize_columns": 1,
  1315. "tools_panelize_rows": 1,
  1316. "tools_panelize_constrain": False,
  1317. "tools_panelize_constrainx": 0.0,
  1318. "tools_panelize_constrainy": 0.0,
  1319. "script_text": "",
  1320. "script_plot": False,
  1321. "script_source_file": "",
  1322. "document_text": "",
  1323. "document_plot": False,
  1324. "document_source_file": "",
  1325. })
  1326. self.options.update(self.defaults) # Copy app defaults to project options
  1327. self.gen_form = None
  1328. self.ger_form = None
  1329. self.exc_form = None
  1330. self.geo_form = None
  1331. self.cnc_form = None
  1332. self.tools_form = None
  1333. self.fa_form = None
  1334. self.on_options_combo_change(0) # Will show the initial form
  1335. # ################################
  1336. # ### Initialize the color box's color in Preferences -> Global -> Color
  1337. # Init Plot Colors
  1338. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1339. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1342. int(self.defaults['global_plot_fill'][7:9], 16))
  1343. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1344. int(self.defaults['global_plot_fill'][7:9], 16))
  1345. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1346. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1347. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1348. # Init Left-Right Selection colors
  1349. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1350. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1352. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1353. int(self.defaults['global_sel_fill'][7:9], 16))
  1354. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1355. int(self.defaults['global_sel_fill'][7:9], 16))
  1356. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1357. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1358. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1359. # Init Right-Left Selection colors
  1360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1361. self.defaults['global_alt_sel_fill'])
  1362. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1363. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1364. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1365. int(self.defaults['global_sel_fill'][7:9], 16))
  1366. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1367. int(self.defaults['global_sel_fill'][7:9], 16))
  1368. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1369. self.defaults['global_alt_sel_line'])
  1370. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1371. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1372. # Init Draw color and Selection Draw Color
  1373. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1374. self.defaults['global_draw_color'])
  1375. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1376. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1377. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1378. self.defaults['global_sel_draw_color'])
  1379. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1380. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1381. # Init Project Items color
  1382. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1383. self.defaults['global_proj_item_color'])
  1384. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1385. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1386. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1387. self.defaults['global_proj_item_dis_color'])
  1388. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1389. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1390. # Init the Annotation CNC Job color
  1391. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1392. self.defaults['cncjob_annotation_fontcolor'])
  1393. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1394. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1395. # Init the Tool Film color
  1396. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1397. self.defaults['tools_film_color'])
  1398. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1399. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1400. # ### End of Data ####
  1401. # ##############################################
  1402. # ######### SETUP OBJECT COLLECTION ############
  1403. # ##############################################
  1404. self.collection = ObjectCollection(self)
  1405. self.ui.project_tab_layout.addWidget(self.collection.view)
  1406. # ### Adjust tabs width ## ##
  1407. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1408. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1409. self.collection.view.setMinimumWidth(290)
  1410. self.log.debug("Finished creating Object Collection.")
  1411. # ###############################################
  1412. # ############# SETUP Plot Area #################
  1413. # ###############################################
  1414. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1415. if self.defaults["global_graphic_engine"] == '3D':
  1416. self.is_legacy = False
  1417. else:
  1418. self.is_legacy = True
  1419. # Matplotlib axis
  1420. self.axes = None
  1421. if show_splash:
  1422. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1423. "Canvas initialization started."),
  1424. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1425. color=QtGui.QColor("gray"))
  1426. start_plot_time = time.time() # debug
  1427. self.plotcanvas = None
  1428. self.app_cursor = None
  1429. self.hover_shapes = None
  1430. self.on_plotcanvas_setup()
  1431. end_plot_time = time.time()
  1432. self.used_time = end_plot_time - start_plot_time
  1433. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1434. if show_splash:
  1435. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1436. "Canvas initialization started.\n"
  1437. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1438. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1439. color=QtGui.QColor("gray"))
  1440. self.ui.splitter.setStretchFactor(1, 2)
  1441. # #################################################################
  1442. # ####################### SYS TRAY ################################
  1443. # #################################################################
  1444. if self.defaults["global_systray_icon"]:
  1445. self.parent_w = QtWidgets.QWidget()
  1446. if self.cmd_line_headless == 1:
  1447. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1448. headless=True,
  1449. parent=self.parent_w)
  1450. else:
  1451. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1452. parent=self.parent_w)
  1453. # ###############################################
  1454. # ############# Worker SETUP ####################
  1455. # ###############################################
  1456. if self.defaults["global_worker_number"]:
  1457. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1458. else:
  1459. self.workers = WorkerStack(workers_number=2)
  1460. self.worker_task.connect(self.workers.add_task)
  1461. self.log.debug("Finished creating Workers crew.")
  1462. # ################################################
  1463. # ############### Activity Monitor ###############
  1464. # ################################################
  1465. if self.defaults["global_activity_icon"] == "Ball green":
  1466. icon = 'share/active_2_static.png'
  1467. movie = "share/active_2.gif"
  1468. elif self.defaults["global_activity_icon"] == "Ball black":
  1469. icon = 'share/active_static.png'
  1470. movie = "share/active.gif"
  1471. elif self.defaults["global_activity_icon"] == "Arrow green":
  1472. icon = 'share/active_3_static.png'
  1473. movie = "share/active_3.gif"
  1474. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1475. icon = 'share/active_4_static.png'
  1476. movie = "share/active_4.gif"
  1477. else:
  1478. icon = 'share/active_static.png'
  1479. movie = "share/active.gif"
  1480. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1481. self.ui.infobar.addWidget(self.activity_view)
  1482. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1483. # ################################################
  1484. # ############### Signal handling ################
  1485. # ################################################
  1486. # ############# Custom signals ##################
  1487. # signal for displaying messages in status bar
  1488. self.inform.connect(self.info)
  1489. # signal to be called when the app is quiting
  1490. self.app_quit.connect(self.quit_application)
  1491. self.message.connect(self.message_dialog)
  1492. self.progress.connect(self.set_progress_bar)
  1493. # signals that are emitted when object state changes
  1494. self.object_created.connect(self.on_object_created)
  1495. self.object_changed.connect(self.on_object_changed)
  1496. self.object_plotted.connect(self.on_object_plotted)
  1497. self.plots_updated.connect(self.on_plots_updated)
  1498. # signals emitted when file state change
  1499. self.file_opened.connect(self.register_recent)
  1500. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1501. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1502. # ############# Standard signals ###################
  1503. # ### Menu
  1504. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1505. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1506. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1507. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1508. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1509. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1510. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1511. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1512. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1513. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1514. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1515. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1516. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1517. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1518. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1519. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1520. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1521. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1522. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1523. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1524. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1525. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1526. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1527. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1528. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1529. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1530. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1531. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1532. self.ui.menufile_exit.triggered.connect(self.final_save)
  1533. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1534. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1535. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1536. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1537. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1538. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1539. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1540. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1541. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1542. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1543. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1544. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1545. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1546. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1547. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1548. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1549. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1550. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1551. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1552. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1553. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1554. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1555. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1556. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1557. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1558. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1559. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1560. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1561. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1562. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1563. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1564. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1565. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1566. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1567. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1568. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1569. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1570. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1571. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1572. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1573. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1574. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1575. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1576. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1577. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1578. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1579. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1580. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1581. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1582. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1583. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1584. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1585. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1586. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1587. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1588. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1589. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1590. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1591. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1592. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1593. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1594. # ToolBar signals
  1595. self.connect_toolbar_signals()
  1596. # Notebook signals
  1597. # make the right click on the notebook tab connect to a function
  1598. self.ui.notebook.setupContextMenu()
  1599. self.ui.notebook.addContextMenu(
  1600. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1601. initial_checked=self.defaults["global_tabs_detachable"])
  1602. # activate initial state
  1603. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1604. # Context Menu
  1605. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1606. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1607. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1608. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1609. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1610. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1611. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1612. self.ui.clearplot.triggered.connect(self.clear_plots)
  1613. self.ui.replot.triggered.connect(self.plot_all)
  1614. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1615. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1616. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1617. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1618. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1619. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1620. # Preferences Plot Area TAB
  1621. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1622. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1623. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1624. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1625. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1626. # ##############################
  1627. # ### GUI PREFERENCES SIGNALS ##
  1628. # ##############################
  1629. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1630. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1631. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1632. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1633. )
  1634. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1635. lambda: self.on_toggle_units(no_pref=False))
  1636. # ###############################################################
  1637. # ################### GUI COLORS SIGNALS ########################
  1638. # ###############################################################
  1639. # Setting plot colors signals
  1640. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1641. self.on_pf_color_entry)
  1642. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1643. self.on_pf_color_button)
  1644. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1645. self.on_pf_color_spinner)
  1646. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1647. self.on_pf_color_slider)
  1648. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1649. self.on_pl_color_entry)
  1650. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1651. self.on_pl_color_button)
  1652. # Setting selection (left - right) colors signals
  1653. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1654. self.on_sf_color_entry)
  1655. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1656. self.on_sf_color_button)
  1657. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1658. self.on_sf_color_spinner)
  1659. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1660. self.on_sf_color_slider)
  1661. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1662. self.on_sl_color_entry)
  1663. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1664. self.on_sl_color_button)
  1665. # Setting selection (right - left) colors signals
  1666. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1667. self.on_alt_sf_color_entry)
  1668. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1669. self.on_alt_sf_color_button)
  1670. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1671. self.on_alt_sf_color_spinner)
  1672. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1673. self.on_alt_sf_color_slider)
  1674. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1675. self.on_alt_sl_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1677. self.on_alt_sl_color_button)
  1678. # Setting Editor Draw colors signals
  1679. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1680. self.on_draw_color_entry)
  1681. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1682. self.on_draw_color_button)
  1683. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1684. self.on_sel_draw_color_entry)
  1685. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1686. self.on_sel_draw_color_button)
  1687. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1688. self.on_proj_color_entry)
  1689. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1690. self.on_proj_color_button)
  1691. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1692. self.on_proj_color_dis_entry)
  1693. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1694. self.on_proj_color_dis_button)
  1695. # ########## workspace setting signals ###########
  1696. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1697. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1698. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1699. # #################################################
  1700. # ############ GUI SETTINGS SIGNALS ###############
  1701. # #################################################
  1702. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1703. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1704. # ########## CNC Job related signals #############
  1705. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1706. self.on_cnc_custom_parameters)
  1707. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1708. self.on_annotation_fontcolor_entry)
  1709. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1710. self.on_annotation_fontcolor_button)
  1711. # ########## Tools related signals #############
  1712. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1713. self.on_film_color_entry)
  1714. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1715. self.on_film_color_button)
  1716. # portability changed signal
  1717. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1718. # Object list
  1719. self.collection.view.activated.connect(self.on_row_activated)
  1720. self.object_status_changed.connect(self.on_collection_updated)
  1721. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1722. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1723. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1724. # Export Excellon parameters.
  1725. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1726. self.on_update_exc_export
  1727. )
  1728. # call it once to make sure it is updated at startup
  1729. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1730. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1731. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1732. self.on_excellon_defaults_button)
  1733. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1734. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1735. self.on_excellon_options_button)
  1736. # when there are arguments at application startup this get launched
  1737. self.args_at_startup[list].connect(self.on_startup_args)
  1738. # ##############################################################
  1739. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1740. # ##############################################################
  1741. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1742. lambda: self.restore_extensions(ext_type='excellon'))
  1743. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='gcode'))
  1745. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gerber'))
  1747. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1748. lambda: self.delete_all_extensions(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gerber'))
  1753. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1754. lambda: self.add_extension(ext_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gerber'))
  1759. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1760. lambda: self.del_extension(ext_type='excellon'))
  1761. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='gcode'))
  1763. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gerber'))
  1765. # connect the 'Apply' buttons from the Preferences/File Associations
  1766. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1767. lambda: self.on_register_files(obj_type='excellon'))
  1768. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='gcode'))
  1770. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gerber'))
  1772. # ##############################################################
  1773. # ###################### KEYWORDS SIGNALS ######################
  1774. # ##############################################################
  1775. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1776. lambda: self.restore_extensions(ext_type='keyword'))
  1777. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1778. lambda: self.delete_all_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1780. lambda: self.add_extension(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1782. lambda: self.del_extension(ext_type='keyword'))
  1783. # splash screen button signal
  1784. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1785. # connect the abort_all_tasks related slots to the related signals
  1786. self.proc_container.idle_flag.connect(self.app_is_idle)
  1787. # signal emitted when a tab is closed in the Plot Area
  1788. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1789. # #####################################################################################
  1790. # ########### FINISHED CONNECTING SIGNALS #############################################
  1791. # #####################################################################################
  1792. self.log.debug("Finished connecting Signals.")
  1793. # #####################################################################################
  1794. # ########################## Other setups #############################################
  1795. # #####################################################################################
  1796. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1797. # depending on from where those tools are called different actions can be done
  1798. self.call_source = 'app'
  1799. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1800. self.tool_tab_locked = False
  1801. # decide if to show or hide the Notebook side of the screen at startup
  1802. if self.defaults["global_project_at_startup"] is True:
  1803. self.ui.splitter.setSizes([1, 1])
  1804. else:
  1805. self.ui.splitter.setSizes([0, 1])
  1806. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1807. self.setup_obj_classes()
  1808. self.setup_recent_items()
  1809. self.setup_component_editor()
  1810. # this does not work in Legacy Mode
  1811. if self.is_legacy is True:
  1812. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1813. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1814. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1815. # #####################################################################################
  1816. # ######################### Auto-complete KEYWORDS ####################################
  1817. # #####################################################################################
  1818. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1819. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1820. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1821. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1822. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1823. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1824. 'mirror', 'ncc',
  1825. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1826. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1827. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1828. 'save', 'save_project',
  1829. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1830. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1831. 'version', 'write_gcode'
  1832. ]
  1833. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1834. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1835. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1836. 'axisoffset',
  1837. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1838. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1839. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1840. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1841. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1842. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1843. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1844. 'spacing_columns',
  1845. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1846. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1847. ]
  1848. self.tcl_keywords = [
  1849. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1850. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1851. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1852. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1853. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1854. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1855. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1856. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1857. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1858. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1859. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1860. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1861. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1862. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1863. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1864. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1865. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1866. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1867. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1868. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1869. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1870. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1871. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1872. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1873. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1874. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1875. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1876. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1877. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1878. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1879. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1880. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1881. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1882. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1883. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1884. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1885. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1886. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1887. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1888. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1889. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1890. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1891. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1892. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1893. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1894. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1895. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1896. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1897. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1898. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1899. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1900. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1901. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1902. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1903. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1904. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1905. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1906. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1907. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1908. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1909. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1910. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1911. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1912. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1913. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1914. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1915. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1916. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1917. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1918. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1919. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1920. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1921. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1922. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1923. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1924. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1925. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1926. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1927. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1928. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1929. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1930. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1931. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1932. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1933. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1934. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1935. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1936. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1937. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1938. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1939. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1940. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1941. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1942. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1943. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1944. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1945. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1946. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1947. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1948. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1949. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1950. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1951. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1952. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1953. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1954. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1955. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1956. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1957. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1958. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1959. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1960. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1961. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1962. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1963. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1964. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1965. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1966. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1967. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1968. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1969. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1970. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1971. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1972. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1973. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1974. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1975. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1976. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1977. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1978. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1979. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1980. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1981. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1982. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1983. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1984. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1985. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1986. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1987. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1988. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1989. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1990. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1991. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1992. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1993. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1994. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1995. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1996. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1997. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1998. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1999. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2000. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2001. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2002. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2003. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2004. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2005. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2006. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2007. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2008. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2009. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2010. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2011. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2012. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2013. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2014. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2015. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2016. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2017. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2018. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2019. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2020. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2021. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2022. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2023. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2024. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2025. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2026. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2027. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2028. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2029. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2030. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2031. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2032. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2033. ]
  2034. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2035. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2036. # ####################################################################################
  2037. # ####################### Shell SETUP ################################################
  2038. # ####################################################################################
  2039. self.shell = FCShell(self, version=self.version)
  2040. self.shell._edit.set_model_data(self.myKeywords)
  2041. self.shell.setWindowIcon(self.ui.app_icon)
  2042. self.shell.setWindowTitle("FlatCAM Shell")
  2043. self.shell.resize(*self.defaults["global_shell_shape"])
  2044. self.shell.append_output("FlatCAM %s - " % self.version)
  2045. self.shell.append_output(_("Type >help< to get started\n\n"))
  2046. self.init_tcl()
  2047. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2048. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2049. self.ui.shell_dock.setWidget(self.shell)
  2050. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2051. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2052. QtWidgets.QDockWidget.DockWidgetFloatable |
  2053. QtWidgets.QDockWidget.DockWidgetClosable)
  2054. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2055. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2056. if self.defaults["global_shell_at_startup"]:
  2057. self.ui.shell_dock.show()
  2058. else:
  2059. self.ui.shell_dock.hide()
  2060. # ##################################################################################
  2061. # ###################### Tools and Plugins #########################################
  2062. # ##################################################################################
  2063. self.dblsidedtool = None
  2064. self.distance_tool = None
  2065. self.distance_min_tool = None
  2066. self.panelize_tool = None
  2067. self.film_tool = None
  2068. self.paste_tool = None
  2069. self.calculator_tool = None
  2070. self.rules_tool = None
  2071. self.sub_tool = None
  2072. self.move_tool = None
  2073. self.cutout_tool = None
  2074. self.ncclear_tool = None
  2075. self.optimal_tool = None
  2076. self.paint_tool = None
  2077. self.transform_tool = None
  2078. self.properties_tool = None
  2079. self.pdf_tool = None
  2080. self.image_tool = None
  2081. self.pcb_wizard_tool = None
  2082. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2083. self.install_tools()
  2084. # ### System Font Parsing ###
  2085. # self.f_parse = ParseFont(self)
  2086. # self.parse_system_fonts()
  2087. # #####################################################################################
  2088. # ######################## Check for updates ##########################################
  2089. # #####################################################################################
  2090. # Separate thread (Not worker)
  2091. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2092. if (self.beta is False or self.beta is None) and \
  2093. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2094. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2095. self.thr2 = QtCore.QThread()
  2096. self.worker_task.emit({'fcn': self.version_check,
  2097. 'params': []})
  2098. self.thr2.start(QtCore.QThread.LowPriority)
  2099. # #####################################################################################
  2100. # ######################### Register files with FlatCAM; #############################
  2101. # ######################### It works only for Windows for now ########################
  2102. # #####################################################################################
  2103. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2104. self.on_register_files()
  2105. # #####################################################################################
  2106. # ###################### Variables for global usage ###################################
  2107. # #####################################################################################
  2108. # coordinates for relative position display
  2109. self.rel_point1 = (0, 0)
  2110. self.rel_point2 = (0, 0)
  2111. # variable to store coordinates
  2112. self.pos = (0, 0)
  2113. self.pos_jump = (0, 0)
  2114. # variable to store mouse coordinates
  2115. self.mouse = [0, 0]
  2116. # decide if we have a double click or single click
  2117. self.doubleclick = False
  2118. # variable to store if a command is active (then the var is not None) and which one it is
  2119. self.command_active = None
  2120. # variable to store the status of moving selection action
  2121. # None value means that it's not an selection action
  2122. # True value = a selection from left to right
  2123. # False value = a selection from right to left
  2124. self.selection_type = None
  2125. # List to store the objects that are currently loaded in FlatCAM
  2126. # This list is updated on each object creation or object delete
  2127. self.all_objects_list = list()
  2128. # List to store the objects that are selected
  2129. self.sel_objects_list = list()
  2130. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2131. self.key_modifiers = None
  2132. # Variable to hold the status of the axis
  2133. self.toggle_axis = True
  2134. # Variable to store the status of the fullscreen event
  2135. self.toggle_fscreen = False
  2136. # Variable to store the status of the code editor
  2137. self.toggle_codeeditor = False
  2138. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2139. self.click_noproject = False
  2140. self.cursor = None
  2141. # Variable to store the GCODE that was edited
  2142. self.gcode_edited = ""
  2143. self.text_editor_tab = None
  2144. # reference for the self.ui.code_editor
  2145. self.reference_code_editor = None
  2146. self.script_code = ''
  2147. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2148. self.preferences_changed_flag = False
  2149. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2150. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2151. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2152. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2153. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2154. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2155. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2156. 'tap', 'xpi']
  2157. self.svg_list = ['svg']
  2158. self.dxf_list = ['dxf']
  2159. self.pdf_list = ['pdf']
  2160. self.prj_list = ['flatprj']
  2161. self.conf_list = ['flatconfig']
  2162. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2163. # flag for polygons not cleared
  2164. self.poly_not_cleared = False
  2165. # VisPy visuals
  2166. self.isHovering = False
  2167. self.notHovering = True
  2168. # Window geometry
  2169. self.x_pos = None
  2170. self.y_pos = None
  2171. self.width = None
  2172. self.height = None
  2173. # Event signals disconnect id holders
  2174. self.mp = None
  2175. self.mm = None
  2176. self.mr = None
  2177. self.mp_zc = None
  2178. # when True, the app has to return from any thread
  2179. self.abort_flag = False
  2180. # set the value used in the Windows Title
  2181. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2182. # this will hold the TCL instance
  2183. self.tcl = None
  2184. # ###############################################################################
  2185. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2186. # ############# It's done only once after install ###############
  2187. # ###############################################################################
  2188. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2189. fac_def_from_file = factory_file.read()
  2190. factory_defaults = json.loads(fac_def_from_file)
  2191. # if the file contain an empty dictionary then save the factory defaults into the file
  2192. if not factory_defaults:
  2193. self.save_factory_defaults(silent=False)
  2194. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2195. initial_lay = 'compact'
  2196. self.on_layout(lay=initial_lay)
  2197. # Set the combobox in Preferences to the current layout
  2198. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2199. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2200. factory_file.close()
  2201. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2202. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2203. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2204. # after the first run, this object should be False
  2205. self.defaults["first_run"] = False
  2206. # ###############################################################################
  2207. # ################# ADDING FlatCAM EDITORS section ##############################
  2208. # ###############################################################################
  2209. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2210. # at the first launch of the App , the editors will not be functional.
  2211. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2212. self.exc_editor = FlatCAMExcEditor(self)
  2213. self.grb_editor = FlatCAMGrbEditor(self)
  2214. self.log.debug("Finished adding FlatCAM Editor's.")
  2215. self.set_ui_title(name=_("New Project - Not saved"))
  2216. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2217. current_platform = platform.architecture()[0]
  2218. if current_platform != '64bit':
  2219. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2220. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2221. # ###############################################################################
  2222. # ####################### Finished the CONSTRUCTOR ##############################
  2223. # ###############################################################################
  2224. App.log.debug("END of constructor. Releasing control.")
  2225. # #####################################################################################
  2226. # ########################## SHOW GUI #################################################
  2227. # #####################################################################################
  2228. # if the app is not started as headless, show it
  2229. if self.cmd_line_headless != 1:
  2230. if show_splash:
  2231. # finish the splash
  2232. self.splash.finish(self.ui)
  2233. settings = QSettings("Open Source", "FlatCAM")
  2234. if settings.contains("maximized_gui"):
  2235. maximized_ui = settings.value('maximized_gui', type=bool)
  2236. if maximized_ui is True:
  2237. self.ui.showMaximized()
  2238. else:
  2239. self.ui.show()
  2240. else:
  2241. self.ui.show()
  2242. if self.defaults["global_systray_icon"]:
  2243. self.trayIcon.show()
  2244. else:
  2245. log.warning("******************* RUNNING HEADLESS *******************")
  2246. # #####################################################################################
  2247. # ########################## START-UP ARGUMENTS #######################################
  2248. # #####################################################################################
  2249. # test if the program was started with a script as parameter
  2250. if self.cmd_line_shellvar:
  2251. try:
  2252. cnt = 0
  2253. command_tcl = 0
  2254. for i in self.cmd_line_shellvar.split(','):
  2255. if i is not None:
  2256. try:
  2257. command_tcl = eval(i)
  2258. except:
  2259. command_tcl = i
  2260. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2261. cnt += 1
  2262. # if there are Windows paths then replace the path separator with a Unix like one
  2263. if sys.platform == 'win32':
  2264. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2265. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2266. except Exception as ext:
  2267. print("ERROR: ", ext)
  2268. sys.exit(2)
  2269. if self.cmd_line_shellfile:
  2270. try:
  2271. if self.ui.shell_dock.isHidden():
  2272. self.ui.shell_dock.show()
  2273. with open(self.cmd_line_shellfile, "r") as myfile:
  2274. if show_splash:
  2275. self.splash.showMessage('%s: %ssec\n%s' % (
  2276. _("Canvas initialization started.\n"
  2277. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2278. _("Executing Tcl Script ...")),
  2279. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2280. color=QtGui.QColor("gray"))
  2281. cmd_line_shellfile_text = myfile.read()
  2282. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2283. except Exception as ext:
  2284. print("ERROR: ", ext)
  2285. sys.exit(2)
  2286. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2287. # the path/file_name must be enclosed in quotes if it contain spaces
  2288. if App.args:
  2289. self.args_at_startup.emit(App.args)
  2290. @staticmethod
  2291. def copy_and_overwrite(from_path, to_path):
  2292. """
  2293. From here:
  2294. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2295. :param from_path: source path
  2296. :param to_path: destination path
  2297. :return: None
  2298. """
  2299. if os.path.exists(to_path):
  2300. shutil.rmtree(to_path)
  2301. try:
  2302. shutil.copytree(from_path, to_path)
  2303. except FileNotFoundError:
  2304. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2305. shutil.copytree(from_new_path, to_path)
  2306. def on_startup_args(self, args, silent=False):
  2307. """
  2308. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2309. :param args: a list containing the application args at startup
  2310. :return: None
  2311. """
  2312. if args is not None:
  2313. args_to_process = args
  2314. else:
  2315. args_to_process = App.args
  2316. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2317. for argument in args_to_process:
  2318. if '.FlatPrj'.lower() in argument.lower():
  2319. try:
  2320. project_name = str(argument)
  2321. if project_name == "":
  2322. if silent is False:
  2323. self.inform.emit(_("Open cancelled."))
  2324. else:
  2325. # self.open_project(project_name)
  2326. run_from_arg = True
  2327. # self.worker_task.emit({'fcn': self.open_project,
  2328. # 'params': [project_name, run_from_arg]})
  2329. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2330. except Exception as e:
  2331. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2332. elif '.FlatConfig'.lower() in argument.lower():
  2333. try:
  2334. file_name = str(argument)
  2335. if file_name == "":
  2336. if silent is False:
  2337. self.inform.emit(_("Open Config file failed."))
  2338. else:
  2339. run_from_arg = True
  2340. # self.worker_task.emit({'fcn': self.open_config_file,
  2341. # 'params': [file_name, run_from_arg]})
  2342. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2343. except Exception as e:
  2344. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2345. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2346. try:
  2347. file_name = str(argument)
  2348. if file_name == "":
  2349. if silent is False:
  2350. self.inform.emit(_("Open Script file failed."))
  2351. else:
  2352. if silent is False:
  2353. self.on_fileopenscript(name=file_name)
  2354. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2355. self.on_filerunscript(name=file_name)
  2356. except Exception as e:
  2357. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2358. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2359. log.debug("App.on_startup_args() --> Quit event.")
  2360. sys.exit()
  2361. elif 'save'.lower() in argument.lower():
  2362. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2363. self.save_defaults()
  2364. else:
  2365. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2366. proc_arg = argument.lower()
  2367. for ext in exc_list:
  2368. proc_ext = ext.replace(' ', '')
  2369. proc_ext = '.%s' % proc_ext
  2370. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2371. file_name = str(argument)
  2372. if file_name == "":
  2373. if silent is False:
  2374. self.inform.emit(_("Open Excellon file failed."))
  2375. else:
  2376. self.on_fileopenexcellon(name=file_name)
  2377. return
  2378. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2379. for ext in gco_list:
  2380. proc_ext = ext.replace(' ', '')
  2381. proc_ext = '.%s' % proc_ext
  2382. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2383. file_name = str(argument)
  2384. if file_name == "":
  2385. if silent is False:
  2386. self.inform.emit(_("Open GCode file failed."))
  2387. else:
  2388. self.on_fileopengcode(name=file_name)
  2389. return
  2390. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2391. for ext in grb_list:
  2392. proc_ext = ext.replace(' ', '')
  2393. proc_ext = '.%s' % proc_ext
  2394. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2395. file_name = str(argument)
  2396. if file_name == "":
  2397. if silent is False:
  2398. self.inform.emit(_("Open Gerber file failed."))
  2399. else:
  2400. self.on_fileopengerber(name=file_name)
  2401. return
  2402. # if it reached here without already returning then the app was registered with a file that it does not
  2403. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2404. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2405. # for arg in args_to_process:
  2406. # if 'FlatCAM.exe' in arg:
  2407. # continue
  2408. # else:
  2409. # sys.exit(2)
  2410. def set_ui_title(self, name):
  2411. """
  2412. Sets the title of the main window.
  2413. :param name: String that store the project path and project name
  2414. :return: None
  2415. """
  2416. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2417. (self.version,
  2418. ('BETA' if self.beta else ''),
  2419. platform.architecture()[0],
  2420. self.engine,
  2421. name)
  2422. )
  2423. def on_theme_change(self, val):
  2424. settings = QSettings("Open Source", "FlatCAM")
  2425. settings.setValue('theme', val)
  2426. # This will write the setting to the platform specific storage.
  2427. del settings
  2428. self.on_app_restart()
  2429. def on_app_restart(self):
  2430. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2431. # be left in the SySTray
  2432. try:
  2433. self.trayIcon.hide()
  2434. except Exception as e:
  2435. pass
  2436. fcTranslate.restart_program(app=self)
  2437. def defaults_read_form(self):
  2438. """
  2439. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2440. :return: None
  2441. """
  2442. for option in self.defaults_form_fields:
  2443. try:
  2444. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2445. except Exception as e:
  2446. log.debug("App.defaults_read_form() --> %s" % str(e))
  2447. def defaults_write_form(self, factor=None, fl_units=None):
  2448. """
  2449. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2450. self.defaults dictionary.
  2451. :param factor: will apply a factor to the values that written in the GUI elements
  2452. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2453. :return: None
  2454. """
  2455. for option in self.defaults:
  2456. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2457. # try:
  2458. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2459. # except KeyError:
  2460. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2461. # # TODO: Rethink this?
  2462. # pass
  2463. def defaults_write_form_field(self, field, factor=None, units=None):
  2464. """
  2465. Basically it is the worker in the self.defaults_write_form()
  2466. :param field: the GUI element in Preferences GUI to be updated
  2467. :param factor: factor to be applied to the field parameter
  2468. :param units: current FLatCAM measuring units
  2469. :return: None, it updates GUI elements
  2470. """
  2471. try:
  2472. if factor is None:
  2473. if units is None:
  2474. self.defaults_form_fields[field].set_value(self.defaults[field])
  2475. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2476. self.defaults_form_fields[field].set_value(self.defaults[field])
  2477. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2478. self.defaults_form_fields[field].set_value(self.defaults[field])
  2479. else:
  2480. if units is None:
  2481. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2482. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2483. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2484. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2485. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2486. except KeyError:
  2487. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2488. # TODO: Rethink this?
  2489. pass
  2490. except AttributeError:
  2491. log.debug(field)
  2492. def clear_pool(self):
  2493. """
  2494. Clear the multiprocessing pool and calls garbage collector.
  2495. :return: None
  2496. """
  2497. self.pool.close()
  2498. self.pool = Pool()
  2499. self.pool_recreated.emit(self.pool)
  2500. gc.collect()
  2501. def install_tools(self):
  2502. """
  2503. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2504. Instantiation of the Tools classes.
  2505. The order that the tools are installed is important as they can depend on each other install position.
  2506. :return: None
  2507. """
  2508. self.dblsidedtool = DblSidedTool(self)
  2509. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2510. self.distance_tool = Distance(self)
  2511. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2512. before=self.ui.menueditorigin,
  2513. separator=False)
  2514. self.distance_min_tool = DistanceMin(self)
  2515. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2516. before=self.ui.menueditorigin,
  2517. separator=True)
  2518. self.panelize_tool = Panelize(self)
  2519. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2520. self.film_tool = Film(self)
  2521. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2522. self.paste_tool = SolderPaste(self)
  2523. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2524. self.calculator_tool = ToolCalculator(self)
  2525. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2526. self.sub_tool = ToolSub(self)
  2527. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2528. self.rules_tool = RulesCheck(self)
  2529. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2530. self.optimal_tool = ToolOptimal(self)
  2531. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2532. self.move_tool = ToolMove(self)
  2533. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2534. before=self.ui.menueditorigin, separator=True)
  2535. self.cutout_tool = CutOut(self)
  2536. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2537. before=self.sub_tool.menuAction)
  2538. self.ncclear_tool = NonCopperClear(self)
  2539. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2540. before=self.sub_tool.menuAction, separator=True)
  2541. self.paint_tool = ToolPaint(self)
  2542. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2543. before=self.sub_tool.menuAction, separator=True)
  2544. self.transform_tool = ToolTransform(self)
  2545. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2546. self.properties_tool = Properties(self)
  2547. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2548. self.pdf_tool = ToolPDF(self)
  2549. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2550. separator=True)
  2551. self.image_tool = ToolImage(self)
  2552. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2553. separator=True)
  2554. self.pcb_wizard_tool = PcbWizard(self)
  2555. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2556. self.log.debug("Tools are installed.")
  2557. def remove_tools(self):
  2558. """
  2559. Will remove all the actions in the Tool menu.
  2560. :return: None
  2561. """
  2562. for act in self.ui.menutool.actions():
  2563. self.ui.menutool.removeAction(act)
  2564. def init_tools(self):
  2565. """
  2566. Initialize the Tool tab in the notebook side of the central widget.
  2567. Remove the actions in the Tools menu.
  2568. Instantiate again the FlatCAM tools (plugins).
  2569. All this is required when changing the layout: standard, compact etc.
  2570. :return: None
  2571. """
  2572. log.debug("init_tools()")
  2573. # delete the data currently in the Tools Tab and the Tab itself
  2574. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2575. if widget is not None:
  2576. widget.deleteLater()
  2577. self.ui.notebook.removeTab(2)
  2578. # rebuild the Tools Tab
  2579. self.ui.tool_tab = QtWidgets.QWidget()
  2580. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2581. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2582. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2583. self.ui.tool_scroll_area = VerticalScrollArea()
  2584. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2585. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2586. # first remove all of them
  2587. self.remove_tools()
  2588. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2589. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2590. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2591. # third install all of them
  2592. self.install_tools()
  2593. self.log.debug("Tools are initialized.")
  2594. # def parse_system_fonts(self):
  2595. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2596. # 'params': []})
  2597. def connect_toolbar_signals(self):
  2598. """
  2599. Reconnect the signals to the actions in the toolbar.
  2600. This has to be done each time after the FlatCAM tools are removed/installed.
  2601. :return: None
  2602. """
  2603. # Toolbar
  2604. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2605. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2606. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2607. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2608. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2609. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2610. self.ui.replot_btn.triggered.connect(self.plot_all)
  2611. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2612. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2613. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2614. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2615. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2616. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2617. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2618. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2619. self.ui.delete_btn.triggered.connect(self.on_delete)
  2620. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2621. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2622. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2623. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2624. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2625. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2626. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2627. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2628. # Tools Toolbar Signals
  2629. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2630. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2631. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2632. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2633. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2634. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2635. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2636. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2637. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2638. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2639. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2640. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2641. def object2editor(self):
  2642. """
  2643. Send the current Geometry or Excellon object (if any) into the it's editor.
  2644. :return: None
  2645. """
  2646. self.report_usage("object2editor()")
  2647. edited_object = self.collection.get_active()
  2648. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2649. isinstance(edited_object, FlatCAMExcellon):
  2650. pass
  2651. else:
  2652. self.inform.emit('[WARNING_NOTCL] %s' %
  2653. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2654. return
  2655. if isinstance(edited_object, FlatCAMGeometry):
  2656. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2657. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2658. # we set the notebook to hidden
  2659. self.ui.splitter.setSizes([0, 1])
  2660. if edited_object.multigeo is True:
  2661. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2662. if len(edited_tools) > 1:
  2663. self.inform.emit('[WARNING_NOTCL] %s' %
  2664. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2665. "is not possible.\n"
  2666. "Edit only one geometry at a time."))
  2667. # determine the tool dia of the selected tool
  2668. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2669. # now find the key in the edited_object.tools that has this tooldia
  2670. multi_tool = 1
  2671. for tool in edited_object.tools:
  2672. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2673. multi_tool = tool
  2674. break
  2675. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2676. else:
  2677. self.geo_editor.edit_fcgeometry(edited_object)
  2678. # set call source to the Editor we go into
  2679. self.call_source = 'geo_editor'
  2680. elif isinstance(edited_object, FlatCAMExcellon):
  2681. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2682. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2683. if self.ui.splitter.sizes()[0] == 0:
  2684. self.ui.splitter.setSizes([1, 1])
  2685. self.exc_editor.edit_fcexcellon(edited_object)
  2686. # set call source to the Editor we go into
  2687. self.call_source = 'exc_editor'
  2688. elif isinstance(edited_object, FlatCAMGerber):
  2689. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2690. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2691. if self.ui.splitter.sizes()[0] == 0:
  2692. self.ui.splitter.setSizes([1, 1])
  2693. self.grb_editor.edit_fcgerber(edited_object)
  2694. # set call source to the Editor we go into
  2695. self.call_source = 'grb_editor'
  2696. # make sure that we can't select another object while in Editor Mode:
  2697. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2698. self.ui.project_frame.setDisabled(True)
  2699. # delete any selection shape that might be active as they are not relevant in Editor
  2700. self.delete_selection_shape()
  2701. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2702. self.ui.plot_tab_area.protectTab(0)
  2703. self.inform.emit('[WARNING_NOTCL] %s' %
  2704. _("Editor is activated ..."))
  2705. self.should_we_save = True
  2706. def editor2object(self, cleanup=None):
  2707. """
  2708. Transfers the Geometry or Excellon from it's editor to the current object.
  2709. :return: None
  2710. """
  2711. self.report_usage("editor2object()")
  2712. # do not update a geometry or excellon object unless it comes out of an editor
  2713. if self.call_source != 'app':
  2714. edited_obj = self.collection.get_active()
  2715. if cleanup is None:
  2716. msgbox = QtWidgets.QMessageBox()
  2717. msgbox.setText(_("Do you want to save the edited object?"))
  2718. msgbox.setWindowTitle(_("Close Editor"))
  2719. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2720. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2721. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2722. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2723. msgbox.setDefaultButton(bt_yes)
  2724. msgbox.exec_()
  2725. response = msgbox.clickedButton()
  2726. if response == bt_yes:
  2727. # clean the Tools Tab
  2728. self.ui.tool_scroll_area.takeWidget()
  2729. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2730. self.ui.notebook.setTabText(2, "Tool")
  2731. if isinstance(edited_obj, FlatCAMGeometry):
  2732. obj_type = "Geometry"
  2733. if cleanup is None:
  2734. self.geo_editor.update_fcgeometry(edited_obj)
  2735. self.geo_editor.update_options(edited_obj)
  2736. self.geo_editor.deactivate()
  2737. # update the geo object options so it is including the bounding box values
  2738. try:
  2739. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2740. edited_obj.options['xmin'] = xmin
  2741. edited_obj.options['ymin'] = ymin
  2742. edited_obj.options['xmax'] = xmax
  2743. edited_obj.options['ymax'] = ymax
  2744. except AttributeError as e:
  2745. self.inform.emit('[WARNING] %s' %
  2746. _("Object empty after edit."))
  2747. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2748. elif isinstance(edited_obj, FlatCAMGerber):
  2749. obj_type = "Gerber"
  2750. if cleanup is None:
  2751. self.grb_editor.update_fcgerber()
  2752. self.grb_editor.update_options(edited_obj)
  2753. self.grb_editor.deactivate_grb_editor()
  2754. # delete the old object (the source object) if it was an empty one
  2755. try:
  2756. if len(edited_obj.solid_geometry) == 0:
  2757. old_name = edited_obj.options['name']
  2758. self.collection.set_active(old_name)
  2759. self.collection.delete_active()
  2760. except TypeError:
  2761. # if the solid_geometry is a single Polygon the len() will not work
  2762. # in any case, falling here means that we have something in the solid_geometry, even if only
  2763. # a single Polygon, therefore we pass this
  2764. pass
  2765. # restore GUI to the Selected TAB
  2766. # Remove anything else in the GUI
  2767. self.ui.selected_scroll_area.takeWidget()
  2768. # Switch notebook to Selected page
  2769. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2770. elif isinstance(edited_obj, FlatCAMExcellon):
  2771. obj_type = "Excellon"
  2772. if cleanup is None:
  2773. self.exc_editor.update_fcexcellon(edited_obj)
  2774. self.exc_editor.update_options(edited_obj)
  2775. self.exc_editor.deactivate()
  2776. # delete the old object (the source object) if it was an empty one
  2777. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2778. old_name = edited_obj.options['name']
  2779. self.collection.set_active(old_name)
  2780. self.collection.delete_active()
  2781. # restore GUI to the Selected TAB
  2782. # Remove anything else in the GUI
  2783. self.ui.tool_scroll_area.takeWidget()
  2784. # Switch notebook to Selected page
  2785. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2786. else:
  2787. self.inform.emit('[WARNING_NOTCL] %s' %
  2788. _("Select a Gerber, Geometry or Excellon Object to update."))
  2789. return
  2790. self.inform.emit('[selected] %s %s' %
  2791. (obj_type, _("is updated, returning to App...")))
  2792. elif response == bt_no:
  2793. # clean the Tools Tab
  2794. self.ui.tool_scroll_area.takeWidget()
  2795. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2796. self.ui.notebook.setTabText(2, "Tool")
  2797. if isinstance(edited_obj, FlatCAMGeometry):
  2798. self.geo_editor.deactivate()
  2799. elif isinstance(edited_obj, FlatCAMGerber):
  2800. self.grb_editor.deactivate_grb_editor()
  2801. elif isinstance(edited_obj, FlatCAMExcellon):
  2802. self.exc_editor.deactivate()
  2803. # set focus on the project tab
  2804. else:
  2805. self.inform.emit('[WARNING_NOTCL] %s' %
  2806. _("Select a Gerber, Geometry or Excellon Object to update."))
  2807. return
  2808. edited_obj.set_ui(edited_obj.ui_type())
  2809. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2810. elif response == bt_cancel:
  2811. return
  2812. else:
  2813. if isinstance(edited_obj, FlatCAMGeometry):
  2814. self.geo_editor.deactivate()
  2815. elif isinstance(edited_obj, FlatCAMGerber):
  2816. self.grb_editor.deactivate_grb_editor()
  2817. elif isinstance(edited_obj, FlatCAMExcellon):
  2818. self.exc_editor.deactivate()
  2819. else:
  2820. self.inform.emit('[WARNING_NOTCL] %s' %
  2821. _("Select a Gerber, Geometry or Excellon Object to update."))
  2822. return
  2823. # if notebook is hidden we show it
  2824. if self.ui.splitter.sizes()[0] == 0:
  2825. self.ui.splitter.setSizes([1, 1])
  2826. # restore the call_source to app
  2827. self.call_source = 'app'
  2828. edited_obj.plot()
  2829. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2830. self.ui.plot_tab_area.protectTab(0)
  2831. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2832. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2833. self.ui.project_frame.setDisabled(False)
  2834. def get_last_folder(self):
  2835. """
  2836. Get the folder path from where the last file was opened.
  2837. :return: String, last opened folder path
  2838. """
  2839. return self.defaults["global_last_folder"]
  2840. def get_last_save_folder(self):
  2841. """
  2842. Get the folder path from where the last file was saved.
  2843. :return: String, last saved folder path
  2844. """
  2845. loc = self.defaults["global_last_save_folder"]
  2846. if loc is None:
  2847. loc = self.defaults["global_last_folder"]
  2848. if loc is None:
  2849. loc = os.path.dirname(__file__)
  2850. return loc
  2851. def report_usage(self, resource):
  2852. """
  2853. Increments usage counter for the given resource
  2854. in self.defaults['global_stats'].
  2855. :param resource: Name of the resource.
  2856. :return: None
  2857. """
  2858. if resource in self.defaults['global_stats']:
  2859. self.defaults['global_stats'][resource] += 1
  2860. else:
  2861. self.defaults['global_stats'][resource] = 1
  2862. def init_tcl(self):
  2863. """
  2864. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2865. :return: None
  2866. """
  2867. if hasattr(self, 'tcl'):
  2868. # self.tcl = None
  2869. # TODO we need to clean non default variables and procedures here
  2870. # new object cannot be used here as it will not remember values created for next passes,
  2871. # because tcl was execudted in old instance of TCL
  2872. pass
  2873. else:
  2874. self.tcl = tk.Tcl()
  2875. self.setup_shell()
  2876. self.log.debug("TCL Shell has been initialized.")
  2877. # TODO: This shouldn't be here.
  2878. class TclErrorException(Exception):
  2879. """
  2880. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2881. """
  2882. pass
  2883. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2884. """
  2885. Shows a message on the FlatCAM Shell
  2886. :param msg: Message to display.
  2887. :param show: Opens the shell.
  2888. :param error: Shows the message as an error.
  2889. :param warning: Shows the message as an warning.
  2890. :param success: Shows the message as an success.
  2891. :param selected: Indicate that something was selected on canvas
  2892. :return: None
  2893. """
  2894. if show:
  2895. self.ui.shell_dock.show()
  2896. try:
  2897. if error:
  2898. self.shell.append_error(msg + "\n")
  2899. elif warning:
  2900. self.shell.append_warning(msg + "\n")
  2901. elif success:
  2902. self.shell.append_success(msg + "\n")
  2903. elif selected:
  2904. self.shell.append_selected(msg + "\n")
  2905. else:
  2906. self.shell.append_output(msg + "\n")
  2907. except AttributeError:
  2908. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2909. def raise_tcl_unknown_error(self, unknownException):
  2910. """
  2911. Raise exception if is different type than TclErrorException
  2912. this is here mainly to show unknown errors inside TCL shell console.
  2913. :param unknownException:
  2914. :return:
  2915. """
  2916. if not isinstance(unknownException, self.TclErrorException):
  2917. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2918. else:
  2919. raise unknownException
  2920. def display_tcl_error(self, error, error_info=None):
  2921. """
  2922. Escape bracket [ with '\' otherwise there is error
  2923. "ERROR: missing close-bracket" instead of real error
  2924. :param error: it may be text or exception
  2925. :param error_info: Some informations about the error
  2926. :return: None
  2927. """
  2928. if isinstance(error, Exception):
  2929. exc_type, exc_value, exc_traceback = error_info
  2930. if not isinstance(error, self.TclErrorException):
  2931. show_trace = 1
  2932. else:
  2933. show_trace = int(self.defaults['global_verbose_error_level'])
  2934. if show_trace > 0:
  2935. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2936. trc_formated = []
  2937. for a in reversed(trc):
  2938. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2939. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2940. else:
  2941. text = "%s" % error
  2942. else:
  2943. text = error
  2944. text = text.replace('[', '\\[').replace('"', '\\"')
  2945. self.tcl.eval('return -code error "%s"' % text)
  2946. def raise_tcl_error(self, text):
  2947. """
  2948. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2949. :param text: text of error
  2950. :return: raise exception
  2951. """
  2952. self.display_tcl_error(text)
  2953. raise self.TclErrorException(text)
  2954. def exec_command(self, text, no_echo=False):
  2955. """
  2956. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2957. Also handles execution in separated threads
  2958. :param text: FlatCAM TclCommand with parameters
  2959. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2960. will create crashes of the _Expandable_Edit widget
  2961. :return: output if there was any
  2962. """
  2963. self.report_usage('exec_command')
  2964. result = self.exec_command_test(text, False, no_echo=no_echo)
  2965. # MS: added this method call so the geometry is updated once the TCL command is executed
  2966. # if no_plot is None:
  2967. # self.plot_all()
  2968. return result
  2969. def exec_command_test(self, text, reraise=True, no_echo=False):
  2970. """
  2971. Same as exec_command(...) with additional control over exceptions.
  2972. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2973. :param text: Input command
  2974. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2975. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2976. will create crashes of the _Expandable_Edit widget
  2977. :return: Output from the command
  2978. """
  2979. tcl_command_string = str(text)
  2980. try:
  2981. if no_echo is False:
  2982. self.shell.open_proccessing() # Disables input box.
  2983. result = self.tcl.eval(str(tcl_command_string))
  2984. if result != 'None' and no_echo is False:
  2985. self.shell.append_output(result + '\n')
  2986. except tk.TclError as e:
  2987. # This will display more precise answer if something in TCL shell fails
  2988. result = self.tcl.eval("set errorInfo")
  2989. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2990. if no_echo is False:
  2991. self.shell.append_error('ERROR: ' + result + '\n')
  2992. # Show error in console and just return or in test raise exception
  2993. if reraise:
  2994. raise e
  2995. finally:
  2996. if no_echo is False:
  2997. self.shell.close_proccessing()
  2998. pass
  2999. return result
  3000. # """
  3001. # Code below is unsused. Saved for later.
  3002. # """
  3003. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3004. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3005. # self.log.debug(parts)
  3006. # try:
  3007. # if parts[0] not in commands:
  3008. # self.shell.append_error("Unknown command\n")
  3009. # return
  3010. #
  3011. # #import inspect
  3012. # #inspect.getargspec(someMethod)
  3013. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3014. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3015. # self.shell.append_error(
  3016. # "Command %s takes %d arguments. %d given.\n" %
  3017. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3018. # )
  3019. # return
  3020. #
  3021. # cmdfcn = commands[parts[0]]["fcn"]
  3022. # cmdconv = commands[parts[0]]["converters"]
  3023. # if len(parts) - 1 > 0:
  3024. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3025. # else:
  3026. # retval = cmdfcn()
  3027. # retfcn = commands[parts[0]]["retfcn"]
  3028. # if retval and retfcn(retval):
  3029. # self.shell.append_output(retfcn(retval) + "\n")
  3030. #
  3031. # except Exception as e:
  3032. # #self.shell.append_error(''.join(traceback.format_exc()))
  3033. # #self.shell.append_error("?\n")
  3034. # self.shell.append_error(str(e) + "\n")
  3035. def info(self, msg):
  3036. """
  3037. Informs the user. Normally on the status bar, optionally
  3038. also on the shell.
  3039. :param msg: Text to write.
  3040. :return: None
  3041. """
  3042. # Type of message in brackets at the beginning of the message.
  3043. match = re.search("\[([^\]]+)\](.*)", msg)
  3044. if match:
  3045. level = match.group(1)
  3046. msg_ = match.group(2)
  3047. self.ui.fcinfo.set_status(str(msg_), level=level)
  3048. if level.lower() == "error":
  3049. self.shell_message(msg, error=True, show=True)
  3050. elif level.lower() == "warning":
  3051. self.shell_message(msg, warning=True, show=True)
  3052. elif level.lower() == "error_notcl":
  3053. self.shell_message(msg, error=True, show=False)
  3054. elif level.lower() == "warning_notcl":
  3055. self.shell_message(msg, warning=True, show=False)
  3056. elif level.lower() == "success":
  3057. self.shell_message(msg, success=True, show=False)
  3058. elif level.lower() == "selected":
  3059. self.shell_message(msg, selected=True, show=False)
  3060. else:
  3061. self.shell_message(msg, show=False)
  3062. else:
  3063. self.ui.fcinfo.set_status(str(msg), level="info")
  3064. # make sure that if the message is to clear the infobar with a space
  3065. # is not printed over and over on the shell
  3066. if msg != '':
  3067. self.shell_message(msg)
  3068. def restore_toolbar_view(self):
  3069. """
  3070. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3071. was saved in the defaults dictionary.
  3072. :return: None
  3073. """
  3074. tb = self.defaults["global_toolbar_view"]
  3075. if tb & 1:
  3076. self.ui.toolbarfile.setVisible(True)
  3077. else:
  3078. self.ui.toolbarfile.setVisible(False)
  3079. if tb & 2:
  3080. self.ui.toolbargeo.setVisible(True)
  3081. else:
  3082. self.ui.toolbargeo.setVisible(False)
  3083. if tb & 4:
  3084. self.ui.toolbarview.setVisible(True)
  3085. else:
  3086. self.ui.toolbarview.setVisible(False)
  3087. if tb & 8:
  3088. self.ui.toolbartools.setVisible(True)
  3089. else:
  3090. self.ui.toolbartools.setVisible(False)
  3091. if tb & 16:
  3092. self.ui.exc_edit_toolbar.setVisible(True)
  3093. else:
  3094. self.ui.exc_edit_toolbar.setVisible(False)
  3095. if tb & 32:
  3096. self.ui.geo_edit_toolbar.setVisible(True)
  3097. else:
  3098. self.ui.geo_edit_toolbar.setVisible(False)
  3099. if tb & 64:
  3100. self.ui.grb_edit_toolbar.setVisible(True)
  3101. else:
  3102. self.ui.grb_edit_toolbar.setVisible(False)
  3103. if tb & 128:
  3104. self.ui.snap_toolbar.setVisible(True)
  3105. else:
  3106. self.ui.snap_toolbar.setVisible(False)
  3107. if tb & 256:
  3108. self.ui.toolbarshell.setVisible(True)
  3109. else:
  3110. self.ui.toolbarshell.setVisible(False)
  3111. def load_defaults(self, filename):
  3112. """
  3113. Loads the aplication's default settings from current_defaults.FlatConfig into
  3114. ``self.defaults``.
  3115. :return: None
  3116. """
  3117. try:
  3118. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3119. options = f.read()
  3120. f.close()
  3121. except IOError:
  3122. self.log.error("Could not load defaults file.")
  3123. self.inform.emit('[ERROR] %s' %
  3124. _("Could not load defaults file."))
  3125. # in case the defaults file can't be loaded, show all toolbars
  3126. self.defaults["global_toolbar_view"] = 511
  3127. return
  3128. try:
  3129. defaults = json.loads(options)
  3130. except:
  3131. # in case the defaults file can't be loaded, show all toolbars
  3132. self.defaults["global_toolbar_view"] = 511
  3133. e = sys.exc_info()[0]
  3134. App.log.error(str(e))
  3135. self.inform.emit('[ERROR] %s' %
  3136. _("Failed to parse defaults file."))
  3137. return
  3138. self.defaults.update(defaults)
  3139. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3140. # restore the toolbar view
  3141. self.restore_toolbar_view()
  3142. def on_import_preferences(self):
  3143. """
  3144. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3145. ``self.defaults``.
  3146. :return: None
  3147. """
  3148. self.report_usage("on_import_preferences")
  3149. App.log.debug("on_import_preferences()")
  3150. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3151. try:
  3152. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3153. directory=self.data_path,
  3154. filter=filter_)
  3155. except TypeError:
  3156. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3157. filter=filter_)
  3158. filename = str(filename)
  3159. if filename == "":
  3160. self.inform.emit('[WARNING_NOTCL] %s' %
  3161. _("FlatCAM preferences import cancelled."))
  3162. else:
  3163. try:
  3164. f = open(filename)
  3165. options = f.read()
  3166. f.close()
  3167. except IOError:
  3168. self.log.error("Could not load defaults file.")
  3169. self.inform.emit('[ERROR_NOTCL] %s' %
  3170. _("Could not load defaults file."))
  3171. return
  3172. try:
  3173. defaults_from_file = json.loads(options)
  3174. except Exception as e:
  3175. e = sys.exc_info()[0]
  3176. App.log.error(str(e))
  3177. self.inform.emit('[ERROR_NOTCL] %s' %
  3178. _("Failed to parse defaults file."))
  3179. return
  3180. self.defaults.update(defaults_from_file)
  3181. self.on_preferences_edited()
  3182. self.inform.emit('[success] %s: %s' %
  3183. (_("Imported Defaults from"), filename))
  3184. def on_export_preferences(self):
  3185. """
  3186. Save the defaults dictionary to a file.
  3187. :return: None
  3188. """
  3189. self.report_usage("on_export_preferences")
  3190. App.log.debug("on_export_preferences()")
  3191. defaults_file_content = None
  3192. self.date = str(datetime.today()).rpartition('.')[0]
  3193. self.date = ''.join(c for c in self.date if c not in ':-')
  3194. self.date = self.date.replace(' ', '_')
  3195. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3196. try:
  3197. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3198. caption=_("Export FlatCAM Preferences"),
  3199. directory=self.data_path + '/preferences_' + self.date,
  3200. filter=filter__
  3201. )
  3202. except TypeError:
  3203. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3204. filter=filter__)
  3205. filename = str(filename)
  3206. defaults_from_file = {}
  3207. if filename == "":
  3208. self.inform.emit('[WARNING_NOTCL] %s' %
  3209. _("FlatCAM preferences export cancelled."))
  3210. return
  3211. else:
  3212. try:
  3213. f = open(filename, 'w')
  3214. defaults_file_content = f.read()
  3215. f.close()
  3216. except PermissionError:
  3217. self.inform.emit('[WARNING] %s' %
  3218. _("Permission denied, saving not possible.\n"
  3219. "Most likely another app is holding the file open and not accessible."))
  3220. return
  3221. except IOError:
  3222. App.log.debug('Creating a new preferences file ...')
  3223. f = open(filename, 'w')
  3224. json.dump({}, f)
  3225. f.close()
  3226. except:
  3227. e = sys.exc_info()[0]
  3228. App.log.error("Could not load defaults file.")
  3229. App.log.error(str(e))
  3230. self.inform.emit('[ERROR_NOTCL] %s' %
  3231. _("Could not load preferences file."))
  3232. return
  3233. try:
  3234. defaults_from_file = json.loads(defaults_file_content)
  3235. except:
  3236. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3237. # Update options
  3238. self.defaults_read_form()
  3239. defaults_from_file.update(self.defaults)
  3240. self.propagate_defaults(silent=True)
  3241. # Save update options
  3242. try:
  3243. f = open(filename, "w")
  3244. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3245. f.close()
  3246. except:
  3247. self.inform.emit('[ERROR_NOTCL] %s' %
  3248. _("Failed to write defaults to file."))
  3249. return
  3250. if self.defaults["global_open_style"] is False:
  3251. self.file_opened.emit("preferences", filename)
  3252. self.file_saved.emit("preferences", filename)
  3253. self.inform.emit('[success] %s: %s' %
  3254. (_("Exported preferences to"), filename))
  3255. def on_preferences_open_folder(self):
  3256. """
  3257. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3258. :return: None
  3259. """
  3260. self.report_usage("on_preferences_open_folder()")
  3261. if sys.platform == 'win32':
  3262. subprocess.Popen('explorer %s' % self.data_path)
  3263. elif sys.platform == 'darwin':
  3264. os.system('open "%s"' % self.data_path)
  3265. else:
  3266. subprocess.Popen(['xdg-open', self.data_path])
  3267. self.inform.emit('[success] %s' %
  3268. _("FlatCAM Preferences Folder opened."))
  3269. def save_geometry(self, x, y, width, height, notebook_width):
  3270. """
  3271. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3272. launch of the application.
  3273. :param x: X position of the main window
  3274. :param y: Y position of the main window
  3275. :param width: width of the main window
  3276. :param height: height of the main window
  3277. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3278. :return: None
  3279. """
  3280. self.defaults["global_def_win_x"] = x
  3281. self.defaults["global_def_win_y"] = y
  3282. self.defaults["global_def_win_w"] = width
  3283. self.defaults["global_def_win_h"] = height
  3284. self.defaults["global_def_notebook_width"] = notebook_width
  3285. self.save_defaults()
  3286. def restore_main_win_geom(self):
  3287. try:
  3288. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3289. self.defaults["global_def_win_y"],
  3290. self.defaults["global_def_win_w"],
  3291. self.defaults["global_def_win_h"])
  3292. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3293. except KeyError as e:
  3294. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3295. def message_dialog(self, title, message, kind="info"):
  3296. """
  3297. Builds and show a custom QMessageBox to be used in FlatCAM.
  3298. :param title: title of the QMessageBox
  3299. :param message: message to be displayed
  3300. :param kind: type of QMessageBox; will display a specific icon.
  3301. :return:
  3302. """
  3303. icon = {"info": QtWidgets.QMessageBox.Information,
  3304. "warning": QtWidgets.QMessageBox.Warning,
  3305. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3306. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3307. dlg.setText(message)
  3308. dlg.exec_()
  3309. def register_recent(self, kind, filename):
  3310. """
  3311. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3312. dictionary.
  3313. :param kind: type of file that was opened
  3314. :param filename: the path and file name for the file that was opened
  3315. :return:
  3316. """
  3317. self.log.debug("register_recent()")
  3318. self.log.debug(" %s" % kind)
  3319. self.log.debug(" %s" % filename)
  3320. record = {'kind': str(kind), 'filename': str(filename)}
  3321. if record in self.recent:
  3322. return
  3323. if record in self.recent_projects:
  3324. return
  3325. if record['kind'] == 'project':
  3326. self.recent_projects.insert(0, record)
  3327. else:
  3328. self.recent.insert(0, record)
  3329. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3330. self.recent.pop()
  3331. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3332. self.recent_projects.pop()
  3333. try:
  3334. f = open(self.data_path + '/recent.json', 'w')
  3335. except IOError:
  3336. App.log.error("Failed to open recent items file for writing.")
  3337. self.inform.emit('[ERROR_NOTCL] %s' %
  3338. _('Failed to open recent files file for writing.'))
  3339. return
  3340. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3341. f.close()
  3342. try:
  3343. fp = open(self.data_path + '/recent_projects.json', 'w')
  3344. except IOError:
  3345. App.log.error("Failed to open recent items file for writing.")
  3346. self.inform.emit('[ERROR_NOTCL] %s' %
  3347. _('Failed to open recent projects file for writing.'))
  3348. return
  3349. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3350. fp.close()
  3351. # Re-build the recent items menu
  3352. self.setup_recent_items()
  3353. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3354. """
  3355. Creates a new specialized FlatCAMObj and attaches it to the application,
  3356. this is, updates the GUI accordingly, any other records and plots it.
  3357. This method is thread-safe.
  3358. Notes:
  3359. * If the name is in use, the self.collection will modify it
  3360. when appending it to the collection. There is no need to handle
  3361. name conflicts here.
  3362. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3363. :type kind: str
  3364. :param name: Name for the object.
  3365. :type name: str
  3366. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3367. The function is called with 2 parameters: the new object and the App instance.
  3368. :type initialize: function
  3369. :param active:
  3370. :param fit:
  3371. :param plot: If to plot the resulting object
  3372. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3373. self.colleaction
  3374. :return: None
  3375. :rtype: None
  3376. """
  3377. App.log.debug("new_object()")
  3378. obj_plot = plot
  3379. obj_autoselected = autoselected
  3380. t0 = time.time() # Debug
  3381. # ## Create object
  3382. classdict = {
  3383. "gerber": FlatCAMGerber,
  3384. "excellon": FlatCAMExcellon,
  3385. "cncjob": FlatCAMCNCjob,
  3386. "geometry": FlatCAMGeometry,
  3387. "script": FlatCAMScript,
  3388. "document": FlatCAMDocument
  3389. }
  3390. App.log.debug("Calling object constructor...")
  3391. obj = classdict[kind](name)
  3392. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3393. # Set options from "Project options" form
  3394. self.options_read_form()
  3395. # IMPORTANT
  3396. # The key names in defaults and options dictionary's are not random:
  3397. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3398. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3399. # the options from project options form into the self.options. After that, below, depending on the type of
  3400. # object that is created, it will strip the name of the object and the underline (if the original key was
  3401. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3402. # "toolchange"
  3403. for option in self.options:
  3404. if option.find(kind + "_") == 0:
  3405. oname = option[len(kind) + 1:]
  3406. obj.options[oname] = self.options[option]
  3407. obj.isHovering = False
  3408. obj.notHovering = True
  3409. # Initialize as per user request
  3410. # User must take care to implement initialize
  3411. # in a thread-safe way as is is likely that we
  3412. # have been invoked in a separate thread.
  3413. t1 = time.time()
  3414. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3415. try:
  3416. return_value = initialize(obj, self)
  3417. except Exception as e:
  3418. msg = '[ERROR_NOTCL] %s' % \
  3419. _("An internal error has ocurred. See shell.\n")
  3420. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3421. msg += traceback.format_exc()
  3422. self.inform.emit(msg)
  3423. # if str(e) == "Empty Geometry":
  3424. # self.inform.emit("[ERROR_NOTCL] )
  3425. # else:
  3426. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3427. return "fail"
  3428. t2 = time.time()
  3429. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3430. if return_value == 'fail':
  3431. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3432. return "fail"
  3433. # Check units and convert if necessary
  3434. # This condition CAN be true because initialize() can change obj.units
  3435. if self.options["units"].upper() != obj.units.upper():
  3436. self.inform.emit('%s: %s' %
  3437. (_("Converting units to "), self.options["units"]))
  3438. obj.convert_units(self.options["units"])
  3439. t3 = time.time()
  3440. self.log.debug("%f seconds converting units." % (t3 - t2))
  3441. # Create the bounding box for the object and then add the results to the obj.options
  3442. # But not for Scripts or for Documents
  3443. if kind != 'document' and kind != 'script':
  3444. try:
  3445. xmin, ymin, xmax, ymax = obj.bounds()
  3446. obj.options['xmin'] = xmin
  3447. obj.options['ymin'] = ymin
  3448. obj.options['xmax'] = xmax
  3449. obj.options['ymax'] = ymax
  3450. except Exception as e:
  3451. log.warning("The object has no bounds properties. %s" % str(e))
  3452. return "fail"
  3453. # update the KeyWords list with the name of the file
  3454. self.myKeywords.append(obj.options['name'])
  3455. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3456. # Move the object to the main thread and let the app know that it is available.
  3457. obj.moveToThread(self.main_thread)
  3458. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3459. return obj
  3460. def new_excellon_object(self):
  3461. """
  3462. Creates a new, blank Excellon object.
  3463. :return: None
  3464. """
  3465. self.report_usage("new_excellon_object()")
  3466. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3467. def new_geometry_object(self):
  3468. """
  3469. Creates a new, blank and single-tool Geometry object.
  3470. :return: None
  3471. """
  3472. self.report_usage("new_geometry_object()")
  3473. def initialize(obj, self):
  3474. obj.multitool = False
  3475. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3476. def new_gerber_object(self):
  3477. """
  3478. Creates a new, blank Gerber object.
  3479. :return: None
  3480. """
  3481. self.report_usage("new_gerber_object()")
  3482. def initialize(grb_obj, self):
  3483. grb_obj.multitool = False
  3484. grb_obj.source_file = []
  3485. grb_obj.multigeo = False
  3486. grb_obj.follow = False
  3487. grb_obj.apertures = {}
  3488. grb_obj.solid_geometry = []
  3489. try:
  3490. grb_obj.options['xmin'] = 0
  3491. grb_obj.options['ymin'] = 0
  3492. grb_obj.options['xmax'] = 0
  3493. grb_obj.options['ymax'] = 0
  3494. except KeyError:
  3495. pass
  3496. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3497. def new_script_object(self, name=None, text=None):
  3498. """
  3499. Creates a new, blank TCL Script object.
  3500. :param name: a name for the new object
  3501. :return: None
  3502. """
  3503. self.report_usage("new_script_object()")
  3504. if text is not None:
  3505. new_source_file = text
  3506. else:
  3507. new_source_file = _(
  3508. "#\n"
  3509. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3510. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3511. "#\n\n"
  3512. "# FlatCAM commands list:\n"
  3513. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3514. "ClearCopper,\n"
  3515. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3516. "GetNames,\n"
  3517. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3518. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3519. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3520. "SubtractPoly,\n"
  3521. "# SubtractRectangle, Version, WriteGCode\n"
  3522. "#\n\n"
  3523. )
  3524. def initialize(obj, self):
  3525. obj.source_file = deepcopy(new_source_file)
  3526. if name is None:
  3527. outname = 'new_script'
  3528. else:
  3529. outname = name
  3530. self.new_object('script', outname, initialize, plot=False)
  3531. def new_document_object(self):
  3532. """
  3533. Creates a new, blank Document object.
  3534. :return: None
  3535. """
  3536. self.report_usage("new_document_object()")
  3537. def initialize(obj, self):
  3538. obj.source_file = ""
  3539. self.new_object('document', 'new_document', initialize, plot=False)
  3540. def on_object_created(self, obj, plot, autoselect):
  3541. """
  3542. Event callback for object creation.
  3543. It will add the new object to the collection. After that it will plot the object in a threaded way
  3544. :param obj: The newly created FlatCAM object.
  3545. :param plot: if the newly create object t obe plotted
  3546. :param autoselect: if the newly created object to be autoselected after creation
  3547. :return: None
  3548. """
  3549. t0 = time.time() # DEBUG
  3550. self.log.debug("on_object_created()")
  3551. # The Collection might change the name if there is a collision
  3552. self.collection.append(obj)
  3553. # after adding the object to the collection always update the list of objects that are in the collection
  3554. self.all_objects_list = self.collection.get_list()
  3555. # self.inform.emit('[selected] %s created & selected: %s' %
  3556. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3557. if obj.kind == 'gerber':
  3558. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3559. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3560. elif obj.kind == 'excellon':
  3561. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3562. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3563. elif obj.kind == 'cncjob':
  3564. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3565. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3566. elif obj.kind == 'geometry':
  3567. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3568. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3569. elif obj.kind == 'script':
  3570. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3571. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3572. elif obj.kind == 'document':
  3573. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3574. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3575. # update the SHELL auto-completer model with the name of the new object
  3576. self.shell._edit.set_model_data(self.myKeywords)
  3577. if autoselect:
  3578. # select the just opened object but deselect the previous ones
  3579. self.collection.set_all_inactive()
  3580. self.collection.set_active(obj.options["name"])
  3581. else:
  3582. self.collection.set_all_inactive()
  3583. # here it is done the object plotting
  3584. def worker_task(t_obj):
  3585. with self.proc_container.new(_("Plotting")):
  3586. if isinstance(t_obj, FlatCAMCNCjob):
  3587. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3588. else:
  3589. t_obj.plot()
  3590. t1 = time.time() # DEBUG
  3591. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3592. self.object_plotted.emit(t_obj)
  3593. # Send to worker
  3594. # self.worker.add_task(worker_task, [self])
  3595. if plot is True:
  3596. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3597. def on_object_changed(self, obj):
  3598. """
  3599. Called whenever the geometry of the object was changed in some way.
  3600. This require the update of it's bounding values so it can be the selected on canvas.
  3601. Update the bounding box data from obj.options
  3602. :param obj: the object that was changed
  3603. :return: None
  3604. """
  3605. xmin, ymin, xmax, ymax = obj.bounds()
  3606. obj.options['xmin'] = xmin
  3607. obj.options['ymin'] = ymin
  3608. obj.options['xmax'] = xmax
  3609. obj.options['ymax'] = ymax
  3610. log.debug("Object changed, updating the bounding box data on self.options")
  3611. # delete the old selection shape
  3612. self.delete_selection_shape()
  3613. self.should_we_save = True
  3614. def on_object_plotted(self, obj):
  3615. """
  3616. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3617. :param obj: object to be fit into view
  3618. :return: None
  3619. """
  3620. self.on_zoom_fit(None)
  3621. def options_read_form(self):
  3622. """
  3623. Same as it's equivalent from the defaults.
  3624. self.options use to store the preferences per project. No longer used.
  3625. :return: None
  3626. """
  3627. for option in self.options_form_fields:
  3628. self.options[option] = self.options_form_fields[option].get_value()
  3629. def options_write_form(self):
  3630. """
  3631. Same as it's equivalent from the defaults.
  3632. self.options use to store the preferences per project. No longer used.
  3633. :return: None
  3634. """
  3635. for option in self.options:
  3636. self.options_write_form_field(option)
  3637. def options_write_form_field(self, field):
  3638. """
  3639. Same as it's equivalent from the defaults.
  3640. self.options use to store the preferences per project. No longer used.
  3641. :return: None
  3642. """
  3643. try:
  3644. self.options_form_fields[field].set_value(self.options[field])
  3645. except KeyError:
  3646. # Changed from error to debug. This allows to have data stored
  3647. # which is not user-editable.
  3648. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3649. pass
  3650. def on_about(self):
  3651. """
  3652. Displays the "about" dialog found in the Menu --> Help.
  3653. :return: None
  3654. """
  3655. self.report_usage("on_about")
  3656. version = self.version
  3657. version_date = self.version_date
  3658. beta = self.beta
  3659. class AboutDialog(QtWidgets.QDialog):
  3660. def __init__(self, parent=None):
  3661. QtWidgets.QDialog.__init__(self, parent)
  3662. # Icon and title
  3663. self.setWindowIcon(parent.app_icon)
  3664. self.setWindowTitle(_("About FlatCAM"))
  3665. self.resize(600, 200)
  3666. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3667. # self.setStyleSheet(
  3668. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3669. # "background-attachment: fixed"
  3670. # )
  3671. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3672. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3673. # palette = QtGui.QPalette()
  3674. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3675. # self.setPalette(palette)
  3676. logo = QtWidgets.QLabel()
  3677. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3678. title = QtWidgets.QLabel(
  3679. "<font size=8><B>FlatCAM</B></font><BR>"
  3680. "{title}<BR>"
  3681. "<BR>"
  3682. "<BR>"
  3683. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3684. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3685. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3686. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3687. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3688. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3689. "<B>{issue}</B></a><BR>".format(
  3690. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3691. devel=_("Development"),
  3692. down=_("DOWNLOAD"),
  3693. issue=_("Issue tracker"))
  3694. )
  3695. title.setOpenExternalLinks(True)
  3696. closebtn = QtWidgets.QPushButton(_("Close"))
  3697. tab_widget = QtWidgets.QTabWidget()
  3698. description_label = QtWidgets.QLabel(
  3699. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3700. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3701. version=version,
  3702. beta=('BETA' if beta else ''),
  3703. date=version_date,
  3704. arch=platform.architecture()[0])
  3705. )
  3706. description_label.setOpenExternalLinks(True)
  3707. license_label = QtWidgets.QLabel(
  3708. _(
  3709. '\n'
  3710. 'Licensed under the MIT license:\n'
  3711. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3712. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3713. 'of this software and associated documentation files (the "Software"), to deal\n'
  3714. 'in the Software without restriction, including without limitation the rights\n'
  3715. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3716. 'copies of the Software, and to permit persons to whom the Software is\n'
  3717. 'furnished to do so, subject to the following conditions:\n\n'
  3718. 'The above copyright notice and this permission notice shall be included in\n'
  3719. 'all copies or substantial portions of the Software.\n\n'
  3720. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3721. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3722. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3723. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3724. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3725. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3726. 'THE SOFTWARE.'
  3727. )
  3728. )
  3729. license_label.setOpenExternalLinks(True)
  3730. attributions_label = QtWidgets.QLabel(
  3731. _(
  3732. 'Some of the icons used are from the following sources: <BR>'
  3733. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3734. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3735. 'title="Flaticon">www.flaticon.com</a></div><br>'
  3736. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3737. )
  3738. )
  3739. # layouts
  3740. layout1 = QtWidgets.QVBoxLayout()
  3741. layout1_1 = QtWidgets.QHBoxLayout()
  3742. layout1_2 = QtWidgets.QHBoxLayout()
  3743. layout2 = QtWidgets.QHBoxLayout()
  3744. layout3 = QtWidgets.QHBoxLayout()
  3745. self.setLayout(layout1)
  3746. layout1.addLayout(layout1_1)
  3747. layout1.addLayout(layout1_2)
  3748. layout1.addLayout(layout2)
  3749. layout1.addLayout(layout3)
  3750. layout1_1.addStretch()
  3751. layout1_1.addWidget(description_label)
  3752. layout1_2.addWidget(tab_widget)
  3753. self.splash_tab = QtWidgets.QWidget()
  3754. self.splash_tab.setObjectName("splash_about")
  3755. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3756. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3757. tab_widget.addTab(self.splash_tab, _("Splash"))
  3758. self.programmmers_tab = QtWidgets.QWidget()
  3759. self.programmmers_tab.setObjectName("programmers_about")
  3760. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3761. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3762. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3763. self.translators_tab = QtWidgets.QWidget()
  3764. self.translators_tab.setObjectName("translators_about")
  3765. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3766. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3767. tab_widget.addTab(self.translators_tab, _("Translators"))
  3768. self.license_tab = QtWidgets.QWidget()
  3769. self.license_tab.setObjectName("license_about")
  3770. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3771. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3772. tab_widget.addTab(self.license_tab, _("License"))
  3773. self.attributions_tab = QtWidgets.QWidget()
  3774. self.attributions_tab.setObjectName("attributions_about")
  3775. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3776. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3777. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3778. self.splash_tab_layout.addWidget(logo, stretch=0)
  3779. self.splash_tab_layout.addWidget(title, stretch=1)
  3780. pal = QtGui.QPalette()
  3781. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3782. self.prog_form_lay = QtWidgets.QFormLayout()
  3783. self.prog_form_lay.setHorizontalSpacing(20)
  3784. prog_widget = QtWidgets.QWidget()
  3785. prog_widget.setLayout(self.prog_form_lay)
  3786. prog_scroll = QtWidgets.QScrollArea()
  3787. prog_scroll.setWidget(prog_widget)
  3788. prog_scroll.setWidgetResizable(True)
  3789. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3790. prog_scroll.setPalette(pal)
  3791. self.programmmers_tab_layout.addWidget(prog_scroll)
  3792. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3793. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3794. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3795. QtWidgets.QLabel('%s' % _("Program Author")))
  3796. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3797. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3798. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3799. QtWidgets.QLabel('%s' % _("Maintainer >= 2019")))
  3800. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3801. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alex Lazar"))
  3802. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3803. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3804. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3805. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3806. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3807. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3808. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3809. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3810. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3811. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3812. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3813. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3814. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3815. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3816. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3817. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3818. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3819. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3820. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3821. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3822. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3823. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3824. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3825. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3826. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3827. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3828. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3829. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3830. self.translator_grid_lay = QtWidgets.QGridLayout()
  3831. # trans_widget = QtWidgets.QWidget()
  3832. # trans_widget.setLayout(self.translator_grid_lay)
  3833. # self.translators_tab_layout.addWidget(trans_widget)
  3834. # self.translators_tab_layout.addStretch()
  3835. trans_widget = QtWidgets.QWidget()
  3836. trans_widget.setLayout(self.translator_grid_lay)
  3837. trans_scroll = QtWidgets.QScrollArea()
  3838. trans_scroll.setWidget(trans_widget)
  3839. trans_scroll.setWidgetResizable(True)
  3840. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3841. trans_scroll.setPalette(pal)
  3842. self.translators_tab_layout.addWidget(trans_scroll)
  3843. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3844. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3845. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3846. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3847. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3848. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3849. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3850. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3851. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3852. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3853. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3854. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3855. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3856. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3857. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3858. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3859. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3860. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3861. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3862. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3863. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3864. self.translator_grid_lay.setColumnStretch(0, 0)
  3865. self.translators_tab_layout.addStretch()
  3866. self.license_tab_layout.addWidget(license_label)
  3867. self.license_tab_layout.addStretch()
  3868. self.attributions_tab_layout.addWidget(attributions_label)
  3869. self.attributions_tab_layout.addStretch()
  3870. layout3.addStretch()
  3871. layout3.addWidget(closebtn)
  3872. closebtn.clicked.connect(self.accept)
  3873. AboutDialog(self.ui).exec_()
  3874. def on_file_savedefaults(self):
  3875. """
  3876. Callback for menu item File->Save Defaults. Saves application default options
  3877. ``self.defaults`` to current_defaults.FlatConfig.
  3878. :return: None
  3879. """
  3880. self.save_defaults()
  3881. # def on_app_exit(self):
  3882. # self.report_usage("on_app_exit()")
  3883. #
  3884. # if self.collection.get_list():
  3885. # msgbox = QtWidgets.QMessageBox()
  3886. # # msgbox.setText("<B>Save changes ...</B>")
  3887. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3888. # "\n"
  3889. # "Do you want to Save the project?")
  3890. # msgbox.setWindowTitle("Save changes")
  3891. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3892. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3893. # QtWidgets.QMessageBox.Cancel)
  3894. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3895. #
  3896. # response = msgbox.exec_()
  3897. #
  3898. # if response == QtWidgets.QMessageBox.Yes:
  3899. # self.on_file_saveprojectas(thread=False)
  3900. # elif response == QtWidgets.QMessageBox.Cancel:
  3901. # return
  3902. # self.save_defaults()
  3903. # else:
  3904. # self.save_defaults()
  3905. # log.debug("Application defaults saved ... Exit event.")
  3906. # QtWidgets.qApp.quit()
  3907. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3908. """
  3909. Saves application default options
  3910. ``self.defaults`` to current_defaults.FlatConfig file.
  3911. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3912. used at the next launch of the application.
  3913. :param silent: whether to display a message in status bar or not; boolean
  3914. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3915. When the application is portable it should be a mobile location.
  3916. :return: None
  3917. """
  3918. self.report_usage("save_defaults")
  3919. if data_path is None:
  3920. data_path = self.data_path
  3921. # Read options from file
  3922. try:
  3923. f = open(data_path + "/current_defaults.FlatConfig")
  3924. defaults_file_content = f.read()
  3925. f.close()
  3926. except:
  3927. e = sys.exc_info()[0]
  3928. App.log.error("Could not load defaults file.")
  3929. App.log.error(str(e))
  3930. self.inform.emit('[ERROR_NOTCL] %s' %
  3931. _("Could not load defaults file."))
  3932. return
  3933. try:
  3934. defaults = json.loads(defaults_file_content)
  3935. except:
  3936. e = sys.exc_info()[0]
  3937. App.log.error("Failed to parse defaults file.")
  3938. App.log.error(str(e))
  3939. self.inform.emit('[ERROR_NOTCL] %s' %
  3940. _("Failed to parse defaults file."))
  3941. return
  3942. # Update options
  3943. self.defaults_read_form()
  3944. defaults.update(self.defaults)
  3945. self.propagate_defaults(silent=True)
  3946. # Save the toolbar view
  3947. tb_status = 0
  3948. if self.ui.toolbarfile.isVisible():
  3949. tb_status += 1
  3950. if self.ui.toolbargeo.isVisible():
  3951. tb_status += 2
  3952. if self.ui.toolbarview.isVisible():
  3953. tb_status += 4
  3954. if self.ui.toolbartools.isVisible():
  3955. tb_status += 8
  3956. if self.ui.exc_edit_toolbar.isVisible():
  3957. tb_status += 16
  3958. if self.ui.geo_edit_toolbar.isVisible():
  3959. tb_status += 32
  3960. if self.ui.grb_edit_toolbar.isVisible():
  3961. tb_status += 64
  3962. if self.ui.snap_toolbar.isVisible():
  3963. tb_status += 128
  3964. if self.ui.toolbarshell.isVisible():
  3965. tb_status += 256
  3966. if first_time is False:
  3967. self.defaults["global_toolbar_view"] = tb_status
  3968. # Save update options
  3969. try:
  3970. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3971. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3972. f.close()
  3973. except Exception as e:
  3974. log.debug("App.save_defaults() --> %s" % str(e))
  3975. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write defaults to file.")}')
  3976. return
  3977. if not silent:
  3978. self.inform.emit(f'[success] {_("Preferences saved.")}')
  3979. def save_factory_defaults(self, silent_message=False, data_path=None):
  3980. """
  3981. Saves application factory default options
  3982. ``self.defaults`` to factory_defaults.FlatConfig.
  3983. It's a one time job done just after the first install.
  3984. :param silent_message: whether to display a message in status bar or not; boolean
  3985. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3986. When the application is portable it should be a mobile location.
  3987. :return: None
  3988. """
  3989. self.report_usage("save_factory_defaults")
  3990. if data_path is None:
  3991. data_path = self.data_path
  3992. # Read options from file
  3993. try:
  3994. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3995. factory_defaults_file_content = f_f_def.read()
  3996. f_f_def.close()
  3997. except:
  3998. e = sys.exc_info()[0]
  3999. App.log.error("Could not load factory defaults file.")
  4000. App.log.error(str(e))
  4001. self.inform.emit(f'[ERROR_NOTCL] {_("Could not load factory defaults file.")}')
  4002. return
  4003. try:
  4004. factory_defaults = json.loads(factory_defaults_file_content)
  4005. except:
  4006. e = sys.exc_info()[0]
  4007. App.log.error("Failed to parse factory defaults file.")
  4008. App.log.error(str(e))
  4009. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to parse factory defaults file.")}')
  4010. return
  4011. # Update options
  4012. self.defaults_read_form()
  4013. factory_defaults.update(self.defaults)
  4014. self.propagate_defaults(silent=True)
  4015. # Save update options
  4016. try:
  4017. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4018. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4019. f_f_def_s.close()
  4020. except Exception as e:
  4021. log.debug(f"App.save_factory_default() save update --> {str(e)}")
  4022. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write factory defaults to file.")}')
  4023. return
  4024. if silent_message is False:
  4025. self.inform.emit(f'{_("Factory defaults saved.")}')
  4026. def final_save(self):
  4027. """
  4028. Callback for doing a preferences save to file whenever the application is about to quit.
  4029. If the project has changes, it will ask the user to save the project.
  4030. :return: None
  4031. """
  4032. if self.save_in_progress:
  4033. self.inform.emit(f'[WARNING_NOTCL] {_("Application is saving the project. Please wait ...")}')
  4034. return
  4035. if self.should_we_save and self.collection.get_list():
  4036. msgbox = QtWidgets.QMessageBox()
  4037. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4038. "\n"
  4039. "Do you want to Save the project?"))
  4040. msgbox.setWindowTitle(_("Save changes"))
  4041. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4042. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4043. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4044. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4045. msgbox.setDefaultButton(bt_yes)
  4046. msgbox.exec_()
  4047. response = msgbox.clickedButton()
  4048. if response == bt_yes:
  4049. try:
  4050. self.trayIcon.hide()
  4051. except:
  4052. pass
  4053. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4054. elif response == bt_no:
  4055. try:
  4056. self.trayIcon.hide()
  4057. except:
  4058. pass
  4059. self.quit_application()
  4060. elif response == bt_cancel:
  4061. return
  4062. else:
  4063. try:
  4064. self.trayIcon.hide()
  4065. except:
  4066. pass
  4067. self.quit_application()
  4068. def quit_application(self):
  4069. """
  4070. Called (as a pyslot or not) when the application is quit.
  4071. :return: None
  4072. """
  4073. self.save_defaults()
  4074. log.debug("App.final_save() --> App Defaults saved.")
  4075. if self.cmd_line_headless != 1:
  4076. # save app state to file
  4077. settings = QSettings("Open Source", "FlatCAM")
  4078. settings.setValue('saved_gui_state', self.ui.saveState())
  4079. settings.setValue('maximized_gui', self.ui.isMaximized())
  4080. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4081. settings.setValue(
  4082. 'notebook_font_size',
  4083. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4084. )
  4085. settings.setValue('axis_font_size',
  4086. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4087. settings.setValue(
  4088. 'textbox_font_size',
  4089. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4090. )
  4091. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4092. # This will write the setting to the platform specific storage.
  4093. del settings
  4094. log.debug("App.final_save() --> App UI state saved.")
  4095. QtWidgets.qApp.quit()
  4096. def on_portable_checked(self, state):
  4097. """
  4098. Callback called when the checkbox in Preferences GUI is checked.
  4099. It will set the application as portable by creating the preferences and recent files in the
  4100. 'config' folder found in the FlatCAM installation folder.
  4101. :param state: boolean, the state of the checkbox when clicked/checked
  4102. :return:
  4103. """
  4104. line_no = 0
  4105. data = None
  4106. if sys.platform != 'win32':
  4107. # this won't work in Linux or MacOS
  4108. return
  4109. # test if the app was frozen and choose the path for the configuration file
  4110. if getattr(sys, "frozen", False) is True:
  4111. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4112. else:
  4113. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4114. config_file = current_data_path + '\\configuration.txt'
  4115. try:
  4116. with open(config_file, 'r') as f:
  4117. try:
  4118. data = f.readlines()
  4119. except Exception as e:
  4120. log.debug('App.__init__() -->%s' % str(e))
  4121. return
  4122. except FileNotFoundError:
  4123. pass
  4124. for line in data:
  4125. line = line.strip('\n')
  4126. param = str(line).rpartition('=')
  4127. if param[0] == 'portable':
  4128. break
  4129. line_no += 1
  4130. if state:
  4131. data[line_no] = 'portable=True\n'
  4132. # create the new defauults files
  4133. # create current_defaults.FlatConfig file if there is none
  4134. try:
  4135. f = open(current_data_path + '/current_defaults.FlatConfig')
  4136. f.close()
  4137. except IOError:
  4138. App.log.debug('Creating empty current_defaults.FlatConfig')
  4139. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4140. json.dump({}, f)
  4141. f.close()
  4142. # create factory_defaults.FlatConfig file if there is none
  4143. try:
  4144. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4145. f.close()
  4146. except IOError:
  4147. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4148. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4149. json.dump({}, f)
  4150. f.close()
  4151. try:
  4152. f = open(current_data_path + '/recent.json')
  4153. f.close()
  4154. except IOError:
  4155. App.log.debug('Creating empty recent.json')
  4156. f = open(current_data_path + '/recent.json', 'w')
  4157. json.dump([], f)
  4158. f.close()
  4159. try:
  4160. fp = open(current_data_path + '/recent_projects.json')
  4161. fp.close()
  4162. except IOError:
  4163. App.log.debug('Creating empty recent_projects.json')
  4164. fp = open(current_data_path + '/recent_projects.json', 'w')
  4165. json.dump([], fp)
  4166. fp.close()
  4167. # save the current defaults to the new defaults file
  4168. self.save_defaults(silent=True, data_path=current_data_path)
  4169. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4170. else:
  4171. data[line_no] = 'portable=False\n'
  4172. with open(config_file, 'w') as f:
  4173. f.writelines(data)
  4174. def on_toggle_shell(self):
  4175. """
  4176. Toggle shell: if is visible close it, if it is closed then open it
  4177. :return:
  4178. """
  4179. self.report_usage("on_toggle_shell()")
  4180. if self.ui.shell_dock.isVisible():
  4181. self.ui.shell_dock.hide()
  4182. else:
  4183. self.ui.shell_dock.show()
  4184. def on_register_files(self, obj_type=None):
  4185. """
  4186. Called whenever there is a need to register file extensions with FlatCAM.
  4187. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4188. :param obj_type: the type of object to be register for.
  4189. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4190. :return: None
  4191. """
  4192. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4193. new_reg_path = 'Software\\Classes\\'
  4194. # find if the current user is admin
  4195. try:
  4196. is_admin = os.getuid() == 0
  4197. except AttributeError:
  4198. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4199. if is_admin is True:
  4200. root_path = winreg.HKEY_LOCAL_MACHINE
  4201. else:
  4202. root_path = winreg.HKEY_CURRENT_USER
  4203. # create the keys
  4204. def set_reg(name, root_path, new_reg_path, value):
  4205. try:
  4206. winreg.CreateKey(root_path, new_reg_path)
  4207. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4208. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4209. return True
  4210. except WindowsError:
  4211. return False
  4212. # delete key in registry
  4213. def delete_reg(root_path, reg_path, key_to_del):
  4214. key_to_del_path = reg_path + key_to_del
  4215. try:
  4216. winreg.DeleteKey(root_path, key_to_del_path)
  4217. return True
  4218. except WindowsError:
  4219. return False
  4220. if obj_type is None or obj_type == 'excellon':
  4221. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4222. exc_list = [x for x in exc_list if x != '']
  4223. # register all keys in the Preferences window
  4224. for ext in exc_list:
  4225. new_k = new_reg_path + '.%s' % ext
  4226. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4227. # and unregister those that are no longer in the Preferences windows but are in the file
  4228. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4229. if ext not in exc_list:
  4230. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4231. # now write the updated extensions to the self.defaults
  4232. # new_ext = ''
  4233. # for ext in exc_list:
  4234. # new_ext = new_ext + ext + ', '
  4235. # self.defaults["fa_excellon"] = new_ext
  4236. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4237. if obj_type is None or obj_type == 'gcode':
  4238. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4239. gco_list = [x for x in gco_list if x != '']
  4240. # register all keys in the Preferences window
  4241. for ext in gco_list:
  4242. new_k = new_reg_path + '.%s' % ext
  4243. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4244. # and unregister those that are no longer in the Preferences windows but are in the file
  4245. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4246. if ext not in gco_list:
  4247. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4248. # now write the updated extensions to the self.defaults
  4249. # new_ext = ''
  4250. # for ext in gco_list:
  4251. # new_ext = new_ext + ext + ', '
  4252. # self.defaults["fa_gcode"] = new_ext
  4253. self.inform.emit('[success] %s' %
  4254. _("Selected GCode file extensions registered with FlatCAM."))
  4255. if obj_type is None or obj_type == 'gerber':
  4256. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4257. grb_list = [x for x in grb_list if x != '']
  4258. # register all keys in the Preferences window
  4259. for ext in grb_list:
  4260. new_k = new_reg_path + '.%s' % ext
  4261. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4262. # and unregister those that are no longer in the Preferences windows but are in the file
  4263. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4264. if ext not in grb_list:
  4265. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4266. # now write the updated extensions to the self.defaults
  4267. # new_ext = ''
  4268. # for ext in grb_list:
  4269. # new_ext = new_ext + ext + ', '
  4270. # self.defaults["fa_gerber"] = new_ext
  4271. self.inform.emit('[success] %s' %
  4272. _("Selected Gerber file extensions registered with FlatCAM."))
  4273. def add_extension(self, ext_type):
  4274. if ext_type == 'excellon':
  4275. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4276. if new_ext == '':
  4277. return
  4278. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4279. if new_ext in old_val:
  4280. return
  4281. old_val.append(new_ext)
  4282. old_val.sort()
  4283. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4284. if ext_type == 'gcode':
  4285. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4286. if new_ext == '':
  4287. return
  4288. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4289. if new_ext in old_val:
  4290. return
  4291. old_val.append(new_ext)
  4292. old_val.sort()
  4293. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4294. if ext_type == 'gerber':
  4295. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4296. if new_ext == '':
  4297. return
  4298. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4299. if new_ext in old_val:
  4300. return
  4301. old_val.append(new_ext)
  4302. old_val.sort()
  4303. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4304. if ext_type == 'keyword':
  4305. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4306. if new_kw == '':
  4307. return
  4308. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4309. if new_kw in old_val:
  4310. return
  4311. old_val.append(new_kw)
  4312. old_val.sort()
  4313. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4314. # update the self.myKeywords so the model is updated
  4315. self.autocomplete_kw_list = \
  4316. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4317. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4318. self.shell._edit.set_model_data(self.myKeywords)
  4319. def del_extension(self, ext_type):
  4320. if ext_type == 'excellon':
  4321. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4322. if new_ext == '':
  4323. return
  4324. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4325. if new_ext not in old_val:
  4326. return
  4327. old_val.remove(new_ext)
  4328. old_val.sort()
  4329. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4330. if ext_type == 'gcode':
  4331. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4332. if new_ext == '':
  4333. return
  4334. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4335. if new_ext not in old_val:
  4336. return
  4337. old_val.remove(new_ext)
  4338. old_val.sort()
  4339. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4340. if ext_type == 'gerber':
  4341. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4342. if new_ext == '':
  4343. return
  4344. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4345. if new_ext not in old_val:
  4346. return
  4347. old_val.remove(new_ext)
  4348. old_val.sort()
  4349. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4350. if ext_type == 'keyword':
  4351. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4352. if new_kw == '':
  4353. return
  4354. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4355. if new_kw not in old_val:
  4356. return
  4357. old_val.remove(new_kw)
  4358. old_val.sort()
  4359. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4360. # update the self.myKeywords so the model is updated
  4361. self.autocomplete_kw_list = \
  4362. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4363. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4364. self.shell._edit.set_model_data(self.myKeywords)
  4365. def restore_extensions(self, ext_type):
  4366. if ext_type == 'excellon':
  4367. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4368. # for the ability to open Excellon files with .txt extension
  4369. new_exc_list = deepcopy(self.exc_list)
  4370. try:
  4371. new_exc_list.remove('txt')
  4372. except ValueError:
  4373. pass
  4374. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4375. if ext_type == 'gcode':
  4376. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4377. if ext_type == 'gerber':
  4378. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4379. if ext_type == 'keyword':
  4380. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4381. # update the self.myKeywords so the model is updated
  4382. self.autocomplete_kw_list = self.default_keywords
  4383. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4384. self.shell._edit.set_model_data(self.myKeywords)
  4385. def delete_all_extensions(self, ext_type):
  4386. if ext_type == 'excellon':
  4387. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4388. if ext_type == 'gcode':
  4389. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4390. if ext_type == 'gerber':
  4391. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4392. if ext_type == 'keyword':
  4393. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4394. # update the self.myKeywords so the model is updated
  4395. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4396. self.shell._edit.set_model_data(self.myKeywords)
  4397. def on_edit_join(self, name=None):
  4398. """
  4399. Callback for Edit->Join. Joins the selected geometry objects into
  4400. a new one.
  4401. :return: None
  4402. """
  4403. self.report_usage("on_edit_join()")
  4404. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4405. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4406. geo_type_list = set()
  4407. objs = self.collection.get_selected()
  4408. if len(objs) < 2:
  4409. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4410. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4411. return 'fail'
  4412. for obj in objs:
  4413. geo_type_list.add(obj.multigeo)
  4414. # if len(geo_type_list) == 1 means that all list elements are the same
  4415. if len(geo_type_list) != 1:
  4416. self.inform.emit('[ERROR] %s' %
  4417. _("Failed join. The Geometry objects are of different types.\n"
  4418. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4419. "convert from one to another and retry joining \n"
  4420. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4421. "the result may not be what was expected. \n"
  4422. "Check the generated GCODE."))
  4423. return
  4424. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4425. if True in geo_type_list:
  4426. def initialize(obj, app):
  4427. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4428. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4429. for v in obj.tools.values():
  4430. v['data']['name'] = obj_name_multi
  4431. self.new_object("geometry", obj_name_multi, initialize)
  4432. else:
  4433. def initialize(obj, app):
  4434. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4435. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4436. for v in obj.tools.values():
  4437. v['data']['name'] = obj_name_single
  4438. self.new_object("geometry", obj_name_single, initialize)
  4439. self.should_we_save = True
  4440. def on_edit_join_exc(self):
  4441. """
  4442. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4443. a new Excellon.
  4444. :return: None
  4445. """
  4446. self.report_usage("on_edit_join_exc()")
  4447. objs = self.collection.get_selected()
  4448. for obj in objs:
  4449. if not isinstance(obj, FlatCAMExcellon):
  4450. self.inform.emit('[ERROR_NOTCL] %s' %
  4451. _("Failed. Excellon joining works only on Excellon objects."))
  4452. return
  4453. if len(objs) < 2:
  4454. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4455. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4456. return 'fail'
  4457. def initialize(obj, app):
  4458. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4459. self.new_object("excellon", 'Combo_Excellon', initialize)
  4460. self.should_we_save = True
  4461. def on_edit_join_grb(self):
  4462. """
  4463. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4464. a new Gerber object.
  4465. :return: None
  4466. """
  4467. self.report_usage("on_edit_join_grb()")
  4468. objs = self.collection.get_selected()
  4469. for obj in objs:
  4470. if not isinstance(obj, FlatCAMGerber):
  4471. self.inform.emit('[ERROR_NOTCL] %s' %
  4472. _("Failed. Gerber joining works only on Gerber objects."))
  4473. return
  4474. if len(objs) < 2:
  4475. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4476. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4477. return 'fail'
  4478. def initialize(obj, app):
  4479. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4480. self.new_object("gerber", 'Combo_Gerber', initialize)
  4481. self.should_we_save = True
  4482. def on_convert_singlegeo_to_multigeo(self):
  4483. """
  4484. Called for converting a Geometry object from single-geo to multi-geo.
  4485. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4486. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4487. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4488. the solid-geometry of that tool.
  4489. :return: None
  4490. """
  4491. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4492. obj = self.collection.get_active()
  4493. if obj is None:
  4494. self.inform.emit('[ERROR_NOTCL] %s' %
  4495. _("Failed. Select a Geometry Object and try again."))
  4496. return
  4497. if not isinstance(obj, FlatCAMGeometry):
  4498. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4499. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4500. return
  4501. obj.multigeo = True
  4502. for tooluid, dict_value in obj.tools.items():
  4503. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4504. if not isinstance(obj.solid_geometry, list):
  4505. obj.solid_geometry = [obj.solid_geometry]
  4506. obj.solid_geometry[:] = []
  4507. obj.plot()
  4508. self.should_we_save = True
  4509. self.inform.emit('[success] %s' %
  4510. _("A Geometry object was converted to MultiGeo type."))
  4511. def on_convert_multigeo_to_singlegeo(self):
  4512. """
  4513. Called for converting a Geometry object from multi-geo to single-geo.
  4514. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4515. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4516. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4517. the solid-geometry of that tool.
  4518. :return: None
  4519. """
  4520. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4521. obj = self.collection.get_active()
  4522. if obj is None:
  4523. self.inform.emit('[ERROR_NOTCL] %s' %
  4524. _("Failed. Select a Geometry Object and try again."))
  4525. return
  4526. if not isinstance(obj, FlatCAMGeometry):
  4527. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4528. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4529. return
  4530. obj.multigeo = False
  4531. total_solid_geometry = []
  4532. for tooluid, dict_value in obj.tools.items():
  4533. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4534. # clear the original geometry
  4535. dict_value['solid_geometry'][:] = []
  4536. obj.solid_geometry = deepcopy(total_solid_geometry)
  4537. obj.plot()
  4538. self.should_we_save = True
  4539. self.inform.emit('[success] %s' %
  4540. _("A Geometry object was converted to SingleGeo type."))
  4541. def on_options_dict_change(self, field):
  4542. """
  4543. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4544. current project. This feature is no longer used.
  4545. :param field:
  4546. :return:
  4547. """
  4548. self.options_write_form_field(field)
  4549. if field == "units":
  4550. self.set_screen_units(self.options['units'])
  4551. def on_defaults_dict_change(self, field):
  4552. """
  4553. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4554. Edit -> Preferences tab window.
  4555. :param field: the key of the self.defaults dictionary that was changed.
  4556. :return: None
  4557. """
  4558. self.defaults_write_form_field(field)
  4559. if field == "units":
  4560. self.set_screen_units(self.defaults['units'])
  4561. def set_screen_units(self, units):
  4562. """
  4563. Set the FlatCAM units on the status bar.
  4564. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4565. :return: None
  4566. """
  4567. self.ui.units_label.setText("[" + units.lower() + "]")
  4568. def on_toggle_units(self, no_pref=False):
  4569. """
  4570. Callback for the Units radio-button change in the Preferences tab.
  4571. Changes the application's default units adn for the project too.
  4572. If changing the project's units, the change propagates to all of
  4573. the objects in the project.
  4574. :return: None
  4575. """
  4576. self.report_usage("on_toggle_units")
  4577. if self.toggle_units_ignore:
  4578. return
  4579. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4580. # If option is the same, then ignore
  4581. if new_units == self.defaults["units"].upper():
  4582. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4583. return
  4584. # Options to scale
  4585. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4586. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4587. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4588. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4589. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4590. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4591. "excellon_editor_slot_lin_pitch",
  4592. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4593. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4594. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4595. "geometry_feedrate_probe", "geometry_startz",
  4596. 'cncjob_tooldia',
  4597. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4598. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4599. "tools_2sided_drilldia", "tools_film_boundary",
  4600. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4601. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4602. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4603. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4604. "tools_transform_offset_y",
  4605. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4606. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4607. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4608. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4609. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4610. def scale_options(sfactor):
  4611. for dim in dimensions:
  4612. if dim == 'excellon_toolchangexy':
  4613. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4614. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4615. coords_xy[0] *= sfactor
  4616. coords_xy[1] *= sfactor
  4617. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4618. elif dim == 'geometry_toolchangexy':
  4619. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4620. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4621. coords_xy[0] *= sfactor
  4622. coords_xy[1] *= sfactor
  4623. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4624. elif dim == 'geometry_cnctooldia':
  4625. tools_diameters = []
  4626. try:
  4627. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4628. tools_diameters = [eval(a) for a in tools_string if a != '']
  4629. except Exception as e:
  4630. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4631. self.options['geometry_cnctooldia'] = ''
  4632. for t in range(len(tools_diameters)):
  4633. tools_diameters[t] *= sfactor
  4634. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4635. elif dim == 'tools_ncctools':
  4636. ncctools = []
  4637. try:
  4638. tools_string = self.defaults["tools_ncctools"].split(",")
  4639. ncctools = [eval(a) for a in tools_string if a != '']
  4640. except Exception as e:
  4641. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4642. self.options['tools_ncctools'] = ''
  4643. for t in range(len(ncctools)):
  4644. ncctools[t] *= sfactor
  4645. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4646. elif dim == 'tools_solderpaste_tools':
  4647. sptools = []
  4648. try:
  4649. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4650. sptools = [eval(a) for a in tools_string if a != '']
  4651. except Exception as e:
  4652. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4653. self.options['tools_solderpaste_tools'] = ""
  4654. for t in range(len(sptools)):
  4655. sptools[t] *= sfactor
  4656. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4657. elif dim == 'tools_solderpaste_xy_toolchange':
  4658. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4659. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4660. sp_coords[0] *= sfactor
  4661. sp_coords[1] *= sfactor
  4662. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4663. elif dim == 'global_gridx' or dim == 'global_gridy':
  4664. if new_units == 'IN':
  4665. val = 0.1
  4666. try:
  4667. val = float(self.defaults[dim]) * sfactor
  4668. except Exception as e:
  4669. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4670. self.options[dim] = float('%.6f' % val)
  4671. else:
  4672. val = 0.1
  4673. try:
  4674. val = float(self.defaults[dim]) * sfactor
  4675. except Exception as e:
  4676. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4677. self.options[dim] = float('%.4f' % val)
  4678. else:
  4679. val = 0.1
  4680. if self.options[dim]:
  4681. try:
  4682. val = float(self.options[dim]) * sfactor
  4683. except Exception as e:
  4684. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4685. self.options[dim] = val
  4686. def scale_defaults(sfactor):
  4687. for dim in dimensions:
  4688. if dim == 'excellon_toolchangexy':
  4689. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4690. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4691. coords_xy[0] *= sfactor
  4692. coords_xy[1] *= sfactor
  4693. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4694. elif dim == 'geometry_toolchangexy':
  4695. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4696. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4697. coords_xy[0] *= sfactor
  4698. coords_xy[1] *= sfactor
  4699. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4700. elif dim == 'geometry_cnctooldia':
  4701. tools_diameters = []
  4702. try:
  4703. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4704. tools_diameters = [eval(a) for a in tools_string if a != '']
  4705. except Exception as e:
  4706. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4707. self.defaults['geometry_cnctooldia'] = ''
  4708. for t in range(len(tools_diameters)):
  4709. tools_diameters[t] *= sfactor
  4710. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4711. elif dim == 'tools_ncctools':
  4712. ncctools = []
  4713. try:
  4714. tools_string = self.defaults["tools_ncctools"].split(",")
  4715. ncctools = [eval(a) for a in tools_string if a != '']
  4716. except Exception as e:
  4717. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4718. self.defaults['tools_ncctools'] = ''
  4719. for t in range(len(ncctools)):
  4720. ncctools[t] *= sfactor
  4721. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4722. elif dim == 'tools_solderpaste_tools':
  4723. sptools = []
  4724. try:
  4725. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4726. sptools = [eval(a) for a in tools_string if a != '']
  4727. except Exception as e:
  4728. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4729. self.defaults['tools_solderpaste_tools'] = ""
  4730. for t in range(len(sptools)):
  4731. sptools[t] *= sfactor
  4732. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4733. elif dim == 'tools_solderpaste_xy_toolchange':
  4734. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4735. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4736. sp_coords[0] *= sfactor
  4737. sp_coords[1] *= sfactor
  4738. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4739. elif dim == 'global_gridx' or dim == 'global_gridy':
  4740. if new_units == 'IN':
  4741. val = 0.1
  4742. try:
  4743. val = float(self.defaults[dim]) * sfactor
  4744. except Exception as e:
  4745. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4746. self.defaults[dim] = float('%.6f' % val)
  4747. else:
  4748. val = 0.1
  4749. try:
  4750. val = float(self.defaults[dim]) * sfactor
  4751. except Exception as e:
  4752. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4753. self.defaults[dim] = float('%.4f' % val)
  4754. else:
  4755. val = 0.1
  4756. if self.defaults[dim]:
  4757. try:
  4758. val = float(self.defaults[dim]) * sfactor
  4759. except Exception as e:
  4760. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4761. self.defaults[dim] = val
  4762. # The scaling factor depending on choice of units.
  4763. factor = 1/25.4
  4764. if new_units == 'MM':
  4765. factor = 25.4
  4766. # Changing project units. Warn user.
  4767. msgbox = QtWidgets.QMessageBox()
  4768. msgbox.setWindowTitle(_("Toggle Units"))
  4769. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4770. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4771. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4772. "properties of all objects to be scaled accordingly.\nContinue?"))
  4773. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4774. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4775. msgbox.setDefaultButton(bt_ok)
  4776. msgbox.exec_()
  4777. response = msgbox.clickedButton()
  4778. if response == bt_ok:
  4779. if no_pref is False:
  4780. self.options_read_form()
  4781. scale_options(factor)
  4782. self.options_write_form()
  4783. self.defaults_read_form()
  4784. scale_defaults(factor)
  4785. self.defaults_write_form(fl_units=new_units)
  4786. # save the defaults to file, some may assume that the conversion is enough and it's not
  4787. self.on_save_button()
  4788. self.should_we_save = True
  4789. # change this only if the workspace is active
  4790. if self.defaults['global_workspace'] is True:
  4791. self.plotcanvas.draw_workspace()
  4792. # adjust the grid values on the main toolbar
  4793. dec = 6 if new_units == 'IN'else 4
  4794. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4795. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4796. if not self.ui.grid_gap_link_cb.isChecked():
  4797. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4798. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4799. for obj in self.collection.get_list():
  4800. obj.convert_units(new_units)
  4801. # make that the properties stored in the object are also updated
  4802. self.object_changed.emit(obj)
  4803. obj.build_ui()
  4804. current = self.collection.get_active()
  4805. if current is not None:
  4806. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4807. if not isinstance(current, FlatCAMGeometry):
  4808. current.to_form()
  4809. self.plot_all()
  4810. self.inform.emit('[success] %s: %s' %
  4811. (_("Converted units to"), new_units))
  4812. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4813. self.set_screen_units(new_units)
  4814. else:
  4815. # Undo toggling
  4816. self.toggle_units_ignore = True
  4817. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4818. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4819. else:
  4820. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4821. self.toggle_units_ignore = False
  4822. self.inform.emit('[WARNING_NOTCL]%s' %
  4823. _(" Units conversion cancelled."))
  4824. self.options_read_form()
  4825. self.defaults_read_form()
  4826. def on_toggle_units_click(self):
  4827. try:
  4828. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4829. except (TypeError, AttributeError):
  4830. pass
  4831. if self.defaults["units"] == 'MM':
  4832. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4833. else:
  4834. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4835. self.on_toggle_units(no_pref=True)
  4836. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4837. lambda: self.on_toggle_units(no_pref=False))
  4838. def on_fullscreen(self, disable=False):
  4839. self.report_usage("on_fullscreen()")
  4840. if self.toggle_fscreen is False and disable is False:
  4841. # self.ui.showFullScreen()
  4842. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4843. a = self.ui.geometry()
  4844. self.x_pos = a.x()
  4845. self.y_pos = a.y()
  4846. self.width = a.width()
  4847. self.height = a.height()
  4848. # set new geometry to full desktop rect
  4849. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4850. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4851. # everything else will not work without this hack. This happen in Windows.
  4852. # https://bugreports.qt.io/browse/QTBUG-41309
  4853. desktop = QtWidgets.QApplication.desktop()
  4854. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4855. rec = desktop.screenGeometry(screen)
  4856. x = rec.x() - 1
  4857. y = rec.y() - 1
  4858. h = rec.height() + 2
  4859. w = rec.width() + 2
  4860. self.ui.setGeometry(x, y, w, h)
  4861. self.ui.show()
  4862. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4863. tb.setVisible(False)
  4864. self.ui.splitter_left.setVisible(False)
  4865. self.toggle_fscreen = True
  4866. elif self.toggle_fscreen is True or disable is True:
  4867. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4868. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4869. self.ui.showNormal()
  4870. self.restore_toolbar_view()
  4871. self.ui.splitter_left.setVisible(True)
  4872. self.toggle_fscreen = False
  4873. def on_toggle_plotarea(self):
  4874. self.report_usage("on_toggle_plotarea()")
  4875. try:
  4876. name = self.ui.plot_tab_area.widget(0).objectName()
  4877. except AttributeError:
  4878. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4879. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4880. self.ui.plot_tab_area.protectTab(0)
  4881. return
  4882. if name != 'plotarea':
  4883. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4884. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4885. self.ui.plot_tab_area.protectTab(0)
  4886. else:
  4887. self.ui.plot_tab_area.closeTab(0)
  4888. def on_toggle_notebook(self):
  4889. if self.ui.splitter.sizes()[0] == 0:
  4890. self.ui.splitter.setSizes([1, 1])
  4891. self.ui.menu_toggle_nb.setChecked(True)
  4892. else:
  4893. self.ui.splitter.setSizes([0, 1])
  4894. self.ui.menu_toggle_nb.setChecked(False)
  4895. def on_toggle_axis(self):
  4896. self.report_usage("on_toggle_axis()")
  4897. if self.toggle_axis is False:
  4898. if self.is_legacy is False:
  4899. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4900. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4901. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4902. parent=self.plotcanvas.view.scene)
  4903. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4904. parent=self.plotcanvas.view.scene)
  4905. # self.plotcanvas.redraw()
  4906. else:
  4907. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4908. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4909. self.plotcanvas.canvas.draw()
  4910. pass
  4911. self.toggle_axis = True
  4912. else:
  4913. if self.is_legacy is False:
  4914. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4915. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4916. # self.plotcanvas.redraw()
  4917. self.plotcanvas.v_line.parent = None
  4918. self.plotcanvas.h_line.parent = None
  4919. else:
  4920. self.plotcanvas.axes.lines[:] = []
  4921. self.plotcanvas.canvas.draw()
  4922. self.toggle_axis = False
  4923. def on_toggle_grid(self):
  4924. self.report_usage("on_toggle_grid()")
  4925. self.ui.grid_snap_btn.trigger()
  4926. def on_options_combo_change(self, sel):
  4927. """
  4928. Called when the combo box to choose between application defaults and
  4929. project option changes value. The corresponding variables are
  4930. copied to the UI.
  4931. :param sel: The option index that was chosen.
  4932. :return: None
  4933. """
  4934. # combo_sel = self.ui.notebook.combo_options.get_active()
  4935. App.log.debug("Options --> %s" % sel)
  4936. # form = [self.defaults_form, self.options_form][sel]
  4937. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4938. if sel == 0:
  4939. self.gen_form = self.ui.general_defaults_form
  4940. self.ger_form = self.ui.gerber_defaults_form
  4941. self.exc_form = self.ui.excellon_defaults_form
  4942. self.geo_form = self.ui.geometry_defaults_form
  4943. self.cnc_form = self.ui.cncjob_defaults_form
  4944. self.tools_form = self.ui.tools_defaults_form
  4945. self.fa_form = self.ui.util_defaults_form
  4946. elif sel == 1:
  4947. self.gen_form = self.ui.general_options_form
  4948. self.ger_form = self.ui.gerber_options_form
  4949. self.exc_form = self.ui.excellon_options_form
  4950. self.geo_form = self.ui.geometry_options_form
  4951. self.cnc_form = self.ui.cncjob_options_form
  4952. self.tools_form = self.ui.tools_options_form
  4953. self.fa_form = self.ui.util_options_form
  4954. else:
  4955. return
  4956. try:
  4957. self.ui.general_scroll_area.takeWidget()
  4958. except:
  4959. self.log.debug("Nothing to remove")
  4960. self.ui.general_scroll_area.setWidget(self.gen_form)
  4961. self.gen_form.show()
  4962. try:
  4963. self.ui.gerber_scroll_area.takeWidget()
  4964. except:
  4965. self.log.debug("Nothing to remove")
  4966. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4967. self.ger_form.show()
  4968. try:
  4969. self.ui.excellon_scroll_area.takeWidget()
  4970. except:
  4971. self.log.debug("Nothing to remove")
  4972. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4973. self.exc_form.show()
  4974. try:
  4975. self.ui.geometry_scroll_area.takeWidget()
  4976. except:
  4977. self.log.debug("Nothing to remove")
  4978. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4979. self.geo_form.show()
  4980. try:
  4981. self.ui.cncjob_scroll_area.takeWidget()
  4982. except:
  4983. self.log.debug("Nothing to remove")
  4984. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4985. self.cnc_form.show()
  4986. try:
  4987. self.ui.tools_scroll_area.takeWidget()
  4988. except:
  4989. self.log.debug("Nothing to remove")
  4990. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4991. self.tools_form.show()
  4992. try:
  4993. self.ui.fa_scroll_area.takeWidget()
  4994. except:
  4995. self.log.debug("Nothing to remove")
  4996. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4997. self.fa_form.show()
  4998. self.log.debug("Finished GUI form initialization.")
  4999. # self.options2form()
  5000. def on_excellon_defaults_button(self):
  5001. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5002. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5003. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5004. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5005. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5006. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5007. log.debug("Excellon app defaults loaded ...")
  5008. def on_excellon_options_button(self):
  5009. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  5010. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  5011. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  5012. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  5013. self.options_form_fields["excellon_zeros"].set_value('L')
  5014. self.options_form_fields["excellon_units"].set_value('INCH')
  5015. log.debug("Excellon options defaults loaded ...")
  5016. def on_update_exc_export(self, state):
  5017. """
  5018. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5019. if the update_excellon_cb checkbox is checked
  5020. :param state: state of the checkbox whose signals is tied to his slot
  5021. :return:
  5022. """
  5023. if state:
  5024. # first try to disconnect
  5025. try:
  5026. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.\
  5027. disconnect(self.on_excellon_format_changed)
  5028. except TypeError:
  5029. pass
  5030. try:
  5031. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.\
  5032. disconnect(self.on_excellon_format_changed)
  5033. except TypeError:
  5034. pass
  5035. try:
  5036. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.\
  5037. disconnect(self.on_excellon_format_changed)
  5038. except TypeError:
  5039. pass
  5040. try:
  5041. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.\
  5042. disconnect(self.on_excellon_format_changed)
  5043. except TypeError:
  5044. pass
  5045. try:
  5046. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5047. disconnect(self.on_excellon_zeros_changed)
  5048. except TypeError:
  5049. pass
  5050. try:
  5051. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5052. disconnect(self.on_excellon_zeros_changed)
  5053. except TypeError:
  5054. pass
  5055. # the connect them
  5056. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.connect(
  5057. self.on_excellon_format_changed)
  5058. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.connect(
  5059. self.on_excellon_format_changed)
  5060. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.connect(
  5061. self.on_excellon_format_changed)
  5062. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.connect(
  5063. self.on_excellon_format_changed)
  5064. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5065. self.on_excellon_zeros_changed)
  5066. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5067. self.on_excellon_units_changed)
  5068. else:
  5069. # disconnect the signals
  5070. try:
  5071. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished. \
  5072. disconnect(self.on_excellon_format_changed)
  5073. except TypeError:
  5074. pass
  5075. try:
  5076. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished. \
  5077. disconnect(self.on_excellon_format_changed)
  5078. except TypeError:
  5079. pass
  5080. try:
  5081. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished. \
  5082. disconnect(self.on_excellon_format_changed)
  5083. except TypeError:
  5084. pass
  5085. try:
  5086. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished. \
  5087. disconnect(self.on_excellon_format_changed)
  5088. except TypeError:
  5089. pass
  5090. try:
  5091. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5092. disconnect(self.on_excellon_zeros_changed)
  5093. except TypeError:
  5094. pass
  5095. try:
  5096. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5097. disconnect(self.on_excellon_zeros_changed)
  5098. except TypeError:
  5099. pass
  5100. def on_excellon_format_changed(self):
  5101. """
  5102. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5103. :return: None
  5104. """
  5105. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5106. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5107. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5108. )
  5109. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5110. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5111. )
  5112. else:
  5113. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5114. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5115. )
  5116. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5117. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5118. )
  5119. def on_excellon_zeros_changed(self):
  5120. """
  5121. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5122. :return: None
  5123. """
  5124. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5125. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5126. )
  5127. def on_excellon_units_changed(self):
  5128. """
  5129. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5130. :return: None
  5131. """
  5132. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5133. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5134. )
  5135. self.on_excellon_format_changed()
  5136. # Setting plot colors handlers
  5137. def on_pf_color_entry(self):
  5138. self.defaults['global_plot_fill'] = \
  5139. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5140. self.defaults['global_plot_fill'][7:9]
  5141. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5142. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5143. def on_pf_color_button(self):
  5144. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5145. c_dialog = QtWidgets.QColorDialog()
  5146. plot_fill_color = c_dialog.getColor(initial=current_color)
  5147. if plot_fill_color.isValid() is False:
  5148. return
  5149. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5150. "background-color:%s" % str(plot_fill_color.name()))
  5151. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5152. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5153. self.defaults['global_plot_fill'] = new_val
  5154. def on_pf_color_spinner(self):
  5155. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5156. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5157. self.defaults['global_plot_fill'] = \
  5158. self.defaults['global_plot_fill'][:7] + \
  5159. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5160. self.defaults['global_plot_line'] = \
  5161. self.defaults['global_plot_line'][:7] + \
  5162. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5163. def on_pf_color_slider(self):
  5164. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5165. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5166. def on_pl_color_entry(self):
  5167. self.defaults['global_plot_line'] = \
  5168. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5169. self.defaults['global_plot_line'][7:9]
  5170. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5171. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5172. def on_pl_color_button(self):
  5173. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5174. # print(current_color)
  5175. c_dialog = QtWidgets.QColorDialog()
  5176. plot_line_color = c_dialog.getColor(initial=current_color)
  5177. if plot_line_color.isValid() is False:
  5178. return
  5179. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5180. "background-color:%s" % str(plot_line_color.name()))
  5181. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5182. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5183. self.defaults['global_plot_line'] = new_val_line
  5184. # Setting selection colors (left - right) handlers
  5185. def on_sf_color_entry(self):
  5186. self.defaults['global_sel_fill'] = \
  5187. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5188. self.defaults['global_sel_fill'][7:9]
  5189. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5190. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5191. def on_sf_color_button(self):
  5192. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5193. c_dialog = QtWidgets.QColorDialog()
  5194. plot_fill_color = c_dialog.getColor(initial=current_color)
  5195. if plot_fill_color.isValid() is False:
  5196. return
  5197. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5198. "background-color:%s" % str(plot_fill_color.name()))
  5199. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5200. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5201. self.defaults['global_sel_fill'] = new_val
  5202. def on_sf_color_spinner(self):
  5203. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5204. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5205. self.defaults['global_sel_fill'] = \
  5206. self.defaults['global_sel_fill'][:7] + \
  5207. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5208. self.defaults['global_sel_line'] = \
  5209. self.defaults['global_sel_line'][:7] + \
  5210. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5211. def on_sf_color_slider(self):
  5212. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5213. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5214. def on_sl_color_entry(self):
  5215. self.defaults['global_sel_line'] = \
  5216. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5217. self.defaults['global_sel_line'][7:9]
  5218. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5219. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5220. def on_sl_color_button(self):
  5221. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5222. c_dialog = QtWidgets.QColorDialog()
  5223. plot_line_color = c_dialog.getColor(initial=current_color)
  5224. if plot_line_color.isValid() is False:
  5225. return
  5226. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5227. "background-color:%s" % str(plot_line_color.name()))
  5228. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5229. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5230. self.defaults['global_sel_line'] = new_val_line
  5231. # Setting selection colors (right - left) handlers
  5232. def on_alt_sf_color_entry(self):
  5233. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5234. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5235. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5236. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5237. def on_alt_sf_color_button(self):
  5238. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5239. c_dialog = QtWidgets.QColorDialog()
  5240. plot_fill_color = c_dialog.getColor(initial=current_color)
  5241. if plot_fill_color.isValid() is False:
  5242. return
  5243. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5244. "background-color:%s" % str(plot_fill_color.name()))
  5245. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5246. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5247. self.defaults['global_alt_sel_fill'] = new_val
  5248. def on_alt_sf_color_spinner(self):
  5249. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5250. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5251. self.defaults['global_alt_sel_fill'] = \
  5252. self.defaults['global_alt_sel_fill'][:7] + \
  5253. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5254. self.defaults['global_alt_sel_line'] = \
  5255. self.defaults['global_alt_sel_line'][:7] + \
  5256. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5257. def on_alt_sf_color_slider(self):
  5258. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5259. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5260. def on_alt_sl_color_entry(self):
  5261. self.defaults['global_alt_sel_line'] = \
  5262. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5263. self.defaults['global_alt_sel_line'][7:9]
  5264. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5265. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5266. def on_alt_sl_color_button(self):
  5267. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5268. c_dialog = QtWidgets.QColorDialog()
  5269. plot_line_color = c_dialog.getColor(initial=current_color)
  5270. if plot_line_color.isValid() is False:
  5271. return
  5272. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5273. "background-color:%s" % str(plot_line_color.name()))
  5274. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5275. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5276. self.defaults['global_alt_sel_line'] = new_val_line
  5277. # Setting Editor colors
  5278. def on_draw_color_entry(self):
  5279. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5280. .draw_color_entry.get_value()
  5281. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5282. "background-color:%s" % str(self.defaults['global_draw_color']))
  5283. def on_draw_color_button(self):
  5284. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5285. c_dialog = QtWidgets.QColorDialog()
  5286. draw_color = c_dialog.getColor(initial=current_color)
  5287. if draw_color.isValid() is False:
  5288. return
  5289. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5290. "background-color:%s" % str(draw_color.name()))
  5291. new_val = str(draw_color.name())
  5292. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5293. self.defaults['global_draw_color'] = new_val
  5294. def on_sel_draw_color_entry(self):
  5295. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5296. .sel_draw_color_entry.get_value()
  5297. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5298. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5299. def on_sel_draw_color_button(self):
  5300. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5301. c_dialog = QtWidgets.QColorDialog()
  5302. sel_draw_color = c_dialog.getColor(initial=current_color)
  5303. if sel_draw_color.isValid() is False:
  5304. return
  5305. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5306. "background-color:%s" % str(sel_draw_color.name()))
  5307. new_val_sel = str(sel_draw_color.name())
  5308. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5309. self.defaults['global_sel_draw_color'] = new_val_sel
  5310. def on_proj_color_entry(self):
  5311. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5312. .proj_color_entry.get_value()
  5313. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5314. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5315. def on_proj_color_button(self):
  5316. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5317. c_dialog = QtWidgets.QColorDialog()
  5318. proj_color = c_dialog.getColor(initial=current_color)
  5319. if proj_color.isValid() is False:
  5320. return
  5321. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5322. "background-color:%s" % str(proj_color.name()))
  5323. new_val_sel = str(proj_color.name())
  5324. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5325. self.defaults['global_proj_item_color'] = new_val_sel
  5326. def on_proj_color_dis_entry(self):
  5327. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5328. .proj_color_dis_entry.get_value()
  5329. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5330. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5331. def on_proj_color_dis_button(self):
  5332. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5333. c_dialog = QtWidgets.QColorDialog()
  5334. proj_color = c_dialog.getColor(initial=current_color)
  5335. if proj_color.isValid() is False:
  5336. return
  5337. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5338. "background-color:%s" % str(proj_color.name()))
  5339. new_val_sel = str(proj_color.name())
  5340. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5341. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5342. def on_annotation_fontcolor_entry(self):
  5343. self.defaults['cncjob_annotation_fontcolor'] = \
  5344. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5345. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5346. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5347. def on_annotation_fontcolor_button(self):
  5348. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5349. c_dialog = QtWidgets.QColorDialog()
  5350. annotation_color = c_dialog.getColor(initial=current_color)
  5351. if annotation_color.isValid() is False:
  5352. return
  5353. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5354. "background-color:%s" % str(annotation_color.name()))
  5355. new_val_sel = str(annotation_color.name())
  5356. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5357. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5358. def on_film_color_entry(self):
  5359. self.defaults['tools_film_color'] = \
  5360. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5361. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5362. "background-color:%s" % str(self.defaults['tools_film_color']))
  5363. def on_film_color_button(self):
  5364. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5365. c_dialog = QtWidgets.QColorDialog()
  5366. film_color = c_dialog.getColor(initial=current_color)
  5367. if film_color.isValid() is False:
  5368. return
  5369. # if new color is different then mark that the Preferences are changed
  5370. if film_color != current_color:
  5371. self.on_preferences_edited()
  5372. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5373. "background-color:%s" % str(film_color.name()))
  5374. new_val_sel = str(film_color.name())
  5375. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5376. self.defaults['tools_film_color'] = new_val_sel
  5377. def on_splash_changed(self, state):
  5378. settings = QSettings("Open Source", "FlatCAM")
  5379. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5380. # This will write the setting to the platform specific storage.
  5381. del settings
  5382. def on_notebook_tab_rmb_click(self, checked):
  5383. self.ui.notebook.set_detachable(val=checked)
  5384. self.defaults["global_tabs_detachable"] = checked
  5385. self.ui.plot_tab_area.set_detachable(val=checked)
  5386. self.defaults["global_tabs_detachable"] = checked
  5387. def on_deselect_all(self):
  5388. self.collection.set_all_inactive()
  5389. self.delete_selection_shape()
  5390. def on_workspace_modified(self):
  5391. self.save_defaults(silent=True)
  5392. self.plotcanvas.draw_workspace()
  5393. def on_workspace(self):
  5394. self.report_usage("on_workspace()")
  5395. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5396. self.plotcanvas.restore_workspace()
  5397. else:
  5398. self.plotcanvas.delete_workspace()
  5399. self.save_defaults(silent=True)
  5400. def on_workspace_menu(self):
  5401. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5402. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5403. else:
  5404. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5405. self.on_workspace()
  5406. def on_layout(self, index=None, lay=None):
  5407. """
  5408. Set the toolbars layout (location)
  5409. :param index:
  5410. :param lay: type of layout to be set on the toolbard
  5411. :return: None
  5412. """
  5413. self.report_usage("on_layout()")
  5414. if lay:
  5415. current_layout = lay
  5416. else:
  5417. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5418. settings = QSettings("Open Source", "FlatCAM")
  5419. settings.setValue('layout', current_layout)
  5420. # This will write the setting to the platform specific storage.
  5421. del settings
  5422. # first remove the toolbars:
  5423. try:
  5424. self.ui.removeToolBar(self.ui.toolbarfile)
  5425. self.ui.removeToolBar(self.ui.toolbargeo)
  5426. self.ui.removeToolBar(self.ui.toolbarview)
  5427. self.ui.removeToolBar(self.ui.toolbarshell)
  5428. self.ui.removeToolBar(self.ui.toolbartools)
  5429. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5430. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5431. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5432. self.ui.removeToolBar(self.ui.snap_toolbar)
  5433. self.ui.removeToolBar(self.ui.toolbarshell)
  5434. except Exception as e:
  5435. pass
  5436. if current_layout == 'standard':
  5437. # ## TOOLBAR INSTALLATION # ##
  5438. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5439. self.ui.toolbarfile.setObjectName('File_TB')
  5440. self.ui.addToolBar(self.ui.toolbarfile)
  5441. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5442. self.ui.toolbargeo.setObjectName('Edit_TB')
  5443. self.ui.addToolBar(self.ui.toolbargeo)
  5444. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5445. self.ui.toolbarview.setObjectName('View_TB')
  5446. self.ui.addToolBar(self.ui.toolbarview)
  5447. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5448. self.ui.toolbarshell.setObjectName('Shell_TB')
  5449. self.ui.addToolBar(self.ui.toolbarshell)
  5450. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5451. self.ui.toolbartools.setObjectName('Tools_TB')
  5452. self.ui.addToolBar(self.ui.toolbartools)
  5453. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5454. # self.ui.exc_edit_toolbar.setVisible(False)
  5455. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5456. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5457. self.ui.addToolBarBreak()
  5458. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5459. # self.ui.geo_edit_toolbar.setVisible(False)
  5460. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5461. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5462. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5463. # self.ui.grb_edit_toolbar.setVisible(False)
  5464. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5465. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5466. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5467. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5468. # self.ui.snap_toolbar.setMaximumHeight(30)
  5469. self.ui.addToolBar(self.ui.snap_toolbar)
  5470. self.ui.corner_snap_btn.setVisible(False)
  5471. self.ui.snap_magnet.setVisible(False)
  5472. elif current_layout == 'compact':
  5473. # ## TOOLBAR INSTALLATION # ##
  5474. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5475. self.ui.toolbarfile.setObjectName('File_TB')
  5476. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5477. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5478. self.ui.toolbargeo.setObjectName('Edit_TB')
  5479. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5480. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5481. self.ui.toolbarshell.setObjectName('Shell_TB')
  5482. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5483. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5484. self.ui.toolbartools.setObjectName('Tools_TB')
  5485. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5486. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5487. # self.ui.geo_edit_toolbar.setVisible(False)
  5488. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5489. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5490. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5491. self.ui.toolbarview.setObjectName('View_TB')
  5492. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5493. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5494. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5495. # self.ui.grb_edit_toolbar.setVisible(False)
  5496. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5497. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5498. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5499. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5500. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5501. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5502. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5503. self.ui.snap_toolbar.setMaximumHeight(30)
  5504. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5505. self.ui.corner_snap_btn.setVisible(True)
  5506. self.ui.snap_magnet.setVisible(True)
  5507. # add all the actions to the toolbars
  5508. self.ui.populate_toolbars()
  5509. # reconnect all the signals to the toolbar actions
  5510. self.connect_toolbar_signals()
  5511. self.ui.grid_snap_btn.setChecked(True)
  5512. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5513. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5514. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5515. self.ui.grid_gap_link_cb.setChecked(True)
  5516. def on_cursor_type(self, val):
  5517. """
  5518. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5519. :return: None
  5520. """
  5521. self.app_cursor.enabled = False
  5522. if val == 'small':
  5523. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5524. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5525. self.app_cursor = self.plotcanvas.new_cursor()
  5526. else:
  5527. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5528. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5529. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5530. if self.ui.grid_snap_btn.isChecked():
  5531. self.app_cursor.enabled = True
  5532. else:
  5533. self.app_cursor.enabled = False
  5534. def on_cnc_custom_parameters(self, signal_text):
  5535. if signal_text == 'Parameters':
  5536. return
  5537. else:
  5538. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5539. def on_save_button(self):
  5540. log.debug("App.on_save_button() --> Saving preferences to file.")
  5541. self.preferences_changed_flag = False
  5542. self.save_defaults(silent=False)
  5543. # load the defaults so they are updated into the app
  5544. self.load_defaults(filename='current_defaults')
  5545. # Re-fresh project options
  5546. self.on_options_app2project()
  5547. settings = QSettings("Open Source", "FlatCAM")
  5548. # save the notebook font size
  5549. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5550. settings.setValue('notebook_font_size', fsize)
  5551. # save the axis font size
  5552. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5553. settings.setValue('axis_font_size', g_fsize)
  5554. # save the textbox font size
  5555. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5556. settings.setValue('textbox_font_size', tb_fsize)
  5557. # This will write the setting to the platform specific storage.
  5558. del settings
  5559. def on_tool_add_keypress(self):
  5560. # ## Current application units in Upper Case
  5561. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5562. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5563. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5564. if notebook_widget_name == 'selected_tab':
  5565. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5566. # Tool add works for Geometry only if Advanced is True in Preferences
  5567. if self.defaults["global_app_level"] == 'a':
  5568. tool_add_popup = FCInputDialog(title="New Tool ...",
  5569. text='Enter a Tool Diameter:',
  5570. min=0.0000, max=99.9999, decimals=4)
  5571. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5572. val, ok = tool_add_popup.get_value()
  5573. if ok:
  5574. if float(val) == 0:
  5575. self.inform.emit('[WARNING_NOTCL] %s' %
  5576. _("Please enter a tool diameter with non-zero value, in Float format."))
  5577. return
  5578. self.collection.get_active().on_tool_add(dia=float(val))
  5579. else:
  5580. self.inform.emit('[WARNING_NOTCL] %s...' %
  5581. _("Adding Tool cancelled"))
  5582. else:
  5583. msgbox = QtWidgets.QMessageBox()
  5584. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5585. "Go to Preferences -> General - Show Advanced Options."))
  5586. msgbox.setWindowTitle("Tool adding ...")
  5587. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5588. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5589. msgbox.setDefaultButton(bt_ok)
  5590. msgbox.exec_()
  5591. # work only if the notebook tab on focus is the Tools_Tab
  5592. if notebook_widget_name == 'tool_tab':
  5593. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5594. # and only if the tool is NCC Tool
  5595. if tool_widget == self.ncclear_tool.toolName:
  5596. self.ncclear_tool.on_add_tool_by_key()
  5597. # and only if the tool is Paint Area Tool
  5598. elif tool_widget == self.paint_tool.toolName:
  5599. self.paint_tool.on_add_tool_by_key()
  5600. # and only if the tool is Solder Paste Dispensing Tool
  5601. elif tool_widget == self.paste_tool.toolName:
  5602. self.paste_tool.on_add_tool_by_key()
  5603. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5604. # See description bellow.
  5605. def on_delete_keypress(self):
  5606. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5607. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5608. if notebook_widget_name == 'selected_tab':
  5609. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5610. self.collection.get_active().on_tool_delete()
  5611. # work only if the notebook tab on focus is the Tools_Tab
  5612. elif notebook_widget_name == 'tool_tab':
  5613. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5614. # and only if the tool is NCC Tool
  5615. if tool_widget == self.ncclear_tool.toolName:
  5616. self.ncclear_tool.on_tool_delete()
  5617. # and only if the tool is Paint Tool
  5618. elif tool_widget == self.paint_tool.toolName:
  5619. self.paint_tool.on_tool_delete()
  5620. # and only if the tool is Solder Paste Dispensing Tool
  5621. elif tool_widget == self.paste_tool.toolName:
  5622. self.paste_tool.on_tool_delete()
  5623. else:
  5624. self.on_delete()
  5625. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5626. # some screens you have to be careful where you hover with your mouse.
  5627. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5628. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5629. # Complicated, I know :)
  5630. def on_delete(self):
  5631. """
  5632. Delete the currently selected FlatCAMObjs.
  5633. :return: None
  5634. """
  5635. self.report_usage("on_delete()")
  5636. response = None
  5637. bt_ok = None
  5638. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5639. # a geometry object before we update it.
  5640. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5641. and self.grb_editor.editor_active is False:
  5642. if self.defaults["global_delete_confirmation"] is True:
  5643. msgbox = QtWidgets.QMessageBox()
  5644. msgbox.setWindowTitle(_("Delete objects"))
  5645. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5646. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5647. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5648. "the selected objects?"))
  5649. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5650. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5651. msgbox.setDefaultButton(bt_ok)
  5652. msgbox.exec_()
  5653. response = msgbox.clickedButton()
  5654. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5655. if self.collection.get_active():
  5656. self.log.debug("App.on_delete()")
  5657. while self.collection.get_active():
  5658. obj_active = self.collection.get_active()
  5659. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5660. if isinstance(obj_active, FlatCAMGerber):
  5661. for el in obj_active.mark_shapes:
  5662. obj_active.mark_shapes[el].clear(update=True)
  5663. obj_active.mark_shapes[el].enabled = False
  5664. # obj_active.mark_shapes[el] = None
  5665. del el
  5666. elif isinstance(obj_active, FlatCAMCNCjob):
  5667. try:
  5668. obj_active.annotation.clear(update=True)
  5669. obj_active.annotation.enabled = False
  5670. except AttributeError:
  5671. pass
  5672. self.delete_first_selected()
  5673. self.inform.emit('%s...' %
  5674. _("Object(s) deleted"))
  5675. # make sure that the selection shape is deleted, too
  5676. self.delete_selection_shape()
  5677. else:
  5678. self.inform.emit(_("Failed. No object(s) selected..."))
  5679. else:
  5680. self.inform.emit(_("Save the work in Editor and try again ..."))
  5681. def delete_first_selected(self):
  5682. # Keep this for later
  5683. try:
  5684. sel_obj = self.collection.get_active()
  5685. name = sel_obj.options["name"]
  5686. isPlotted = sel_obj.options["plot"]
  5687. except AttributeError:
  5688. self.log.debug("Nothing selected for deletion")
  5689. return
  5690. if self.is_legacy is True:
  5691. # Remove plot only if the object was plotted otherwise delaxes will fail
  5692. if isPlotted:
  5693. try:
  5694. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5695. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5696. except Exception as e:
  5697. log.debug("App.delete_first_selected() --> %s" % str(e))
  5698. self.plotcanvas.auto_adjust_axes()
  5699. # Remove from dictionary
  5700. self.collection.delete_active()
  5701. # Clear form
  5702. self.setup_component_editor()
  5703. self.inform.emit('%s: %s' %
  5704. (_("Object deleted"), name))
  5705. def on_set_origin(self):
  5706. """
  5707. Set the origin to the left mouse click position
  5708. :return: None
  5709. """
  5710. # display the message for the user
  5711. # and ask him to click on the desired position
  5712. self.report_usage("on_set_origin()")
  5713. def origin_replot():
  5714. def worker_task():
  5715. with self.proc_container.new('%s...' % _("Plotting")):
  5716. for obj in self.collection.get_list():
  5717. obj.plot()
  5718. self.plotcanvas.fit_view()
  5719. if self.is_legacy:
  5720. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5721. else:
  5722. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5723. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5724. self.inform.emit(_('Click to set the origin ...'))
  5725. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5726. # first disconnect it as it may have been used by something else
  5727. try:
  5728. self.replot_signal.disconnect()
  5729. except TypeError:
  5730. pass
  5731. self.replot_signal[list].connect(origin_replot)
  5732. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5733. """
  5734. :param event:
  5735. :param location:
  5736. :param noplot:
  5737. :param use_thread:
  5738. :return:
  5739. """
  5740. noplot_sig = noplot
  5741. def worker_task():
  5742. with self.proc_container.new(_("Setting Origin...")):
  5743. for obj in self.collection.get_list():
  5744. obj.offset((x, y))
  5745. self.object_changed.emit(obj)
  5746. # Update the object bounding box options
  5747. a, b, c, d = obj.bounds()
  5748. obj.options['xmin'] = a
  5749. obj.options['ymin'] = b
  5750. obj.options['xmax'] = c
  5751. obj.options['ymax'] = d
  5752. self.inform.emit('[success] %s...' %
  5753. _('Origin set'))
  5754. if noplot_sig is False:
  5755. self.replot_signal.emit([])
  5756. if location is not None:
  5757. if len(location) != 2:
  5758. self.inform.emit('[ERROR_NOTCL] %s...' %
  5759. _("Origin coordinates specified but incomplete."))
  5760. return 'fail'
  5761. x, y = location
  5762. if use_thread is True:
  5763. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5764. else:
  5765. worker_task()
  5766. self.should_we_save = True
  5767. return
  5768. if event.button == 1:
  5769. if self.is_legacy is False:
  5770. event_pos = event.pos
  5771. else:
  5772. event_pos = (event.xdata, event.ydata)
  5773. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5774. if self.grid_status() == True:
  5775. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5776. else:
  5777. pos = pos_canvas
  5778. x = 0 - pos[0]
  5779. y = 0 - pos[1]
  5780. if use_thread is True:
  5781. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5782. else:
  5783. worker_task()
  5784. self.should_we_save = True
  5785. def on_jump_to(self, custom_location=None, fit_center=True):
  5786. """
  5787. Jump to a location by setting the mouse cursor location
  5788. :return:
  5789. """
  5790. self.report_usage("on_jump_to()")
  5791. # if self.is_legacy is True:
  5792. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5793. # return
  5794. if not custom_location:
  5795. dia_box_location = None
  5796. try:
  5797. dia_box_location = eval(self.clipboard.text())
  5798. except Exception as e:
  5799. pass
  5800. if type(dia_box_location) == tuple:
  5801. dia_box_location = str(dia_box_location)
  5802. else:
  5803. dia_box_location = None
  5804. dia_box = Dialog_box(title=_("Jump to ..."),
  5805. label=_("Enter the coordinates in format X,Y:"),
  5806. icon=QtGui.QIcon('share/jump_to16.png'),
  5807. initial_text=dia_box_location)
  5808. if dia_box.ok is True:
  5809. try:
  5810. location = eval(dia_box.location)
  5811. if not isinstance(location, tuple):
  5812. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5813. return
  5814. except:
  5815. return
  5816. else:
  5817. return
  5818. else:
  5819. location = custom_location
  5820. if fit_center:
  5821. self.plotcanvas.fit_center(loc=location)
  5822. cursor = QtGui.QCursor()
  5823. if self.is_legacy is False:
  5824. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5825. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5826. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5827. cursor.setPos(j_pos[0], j_pos[1])
  5828. else:
  5829. # find the canvas origin which is in the top left corner
  5830. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5831. # determine the coordinates for the lowest left point of the canvas
  5832. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5833. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5834. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5835. # canvas) and the point (width, height) is in the top-right location
  5836. loc = self.plotcanvas.axes.transData.transform_point(location)
  5837. j_pos = (x0 + loc[0], y0 - loc[1])
  5838. cursor.setPos(j_pos[0], j_pos[1])
  5839. if self.grid_status() == True:
  5840. # Update cursor
  5841. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5842. symbol='++', edge_color=self.cursor_color_3D,
  5843. size=self.defaults["global_cursor_size"])
  5844. # Set the position label
  5845. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5846. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5847. # Set the relative position label
  5848. dx = location[0] - float(self.rel_point1[0])
  5849. dy = location[1] - float(self.rel_point1[1])
  5850. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5851. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5852. self.inform.emit('[success] %s' %
  5853. _("Done."))
  5854. return location
  5855. def on_copy_object(self):
  5856. self.report_usage("on_copy_object()")
  5857. def initialize(obj_init, app):
  5858. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5859. try:
  5860. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5861. except AttributeError:
  5862. pass
  5863. try:
  5864. obj_init.apertures = deepcopy(obj.apertures)
  5865. except AttributeError:
  5866. pass
  5867. try:
  5868. if obj.tools:
  5869. obj_init.tools = deepcopy(obj.tools)
  5870. except Exception as e:
  5871. log.debug("App.on_copy_object() --> %s" % str(e))
  5872. def initialize_excellon(obj_init, app):
  5873. obj_init.tools = deepcopy(obj.tools)
  5874. # drills are offset, so they need to be deep copied
  5875. obj_init.drills = deepcopy(obj.drills)
  5876. # slots are offset, so they need to be deep copied
  5877. obj_init.slots = deepcopy(obj.slots)
  5878. obj_init.create_geometry()
  5879. def initialize_script(obj_init, app_obj):
  5880. obj_init.source_file = deepcopy(obj.source_file)
  5881. def initialize_document(obj_init, app_obj):
  5882. obj_init.source_file = deepcopy(obj.source_file)
  5883. for obj in self.collection.get_selected():
  5884. obj_name = obj.options["name"]
  5885. try:
  5886. if isinstance(obj, FlatCAMExcellon):
  5887. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5888. elif isinstance(obj, FlatCAMGerber):
  5889. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5890. elif isinstance(obj, FlatCAMGeometry):
  5891. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5892. elif isinstance(obj, FlatCAMScript):
  5893. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5894. elif isinstance(obj, FlatCAMDocument):
  5895. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5896. except Exception as e:
  5897. return "Operation failed: %s" % str(e)
  5898. def on_copy_object2(self, custom_name):
  5899. def initialize_geometry(obj_init, app):
  5900. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5901. try:
  5902. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5903. except AttributeError:
  5904. pass
  5905. try:
  5906. obj_init.apertures = deepcopy(obj.apertures)
  5907. except AttributeError:
  5908. pass
  5909. try:
  5910. if obj.tools:
  5911. obj_init.tools = deepcopy(obj.tools)
  5912. except Exception as e:
  5913. log.debug("on_copy_object2() --> %s" % str(e))
  5914. def initialize_gerber(obj_init, app):
  5915. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5916. obj_init.apertures = deepcopy(obj.apertures)
  5917. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5918. def initialize_excellon(obj_init, app):
  5919. obj_init.tools = deepcopy(obj.tools)
  5920. # drills are offset, so they need to be deep copied
  5921. obj_init.drills = deepcopy(obj.drills)
  5922. # slots are offset, so they need to be deep copied
  5923. obj_init.slots = deepcopy(obj.slots)
  5924. obj_init.create_geometry()
  5925. for obj in self.collection.get_selected():
  5926. obj_name = obj.options["name"]
  5927. try:
  5928. if isinstance(obj, FlatCAMExcellon):
  5929. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5930. elif isinstance(obj, FlatCAMGerber):
  5931. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5932. elif isinstance(obj, FlatCAMGeometry):
  5933. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5934. except Exception as e:
  5935. return "Operation failed: %s" % str(e)
  5936. def on_rename_object(self, text):
  5937. self.report_usage("on_rename_object()")
  5938. named_obj = self.collection.get_active()
  5939. for obj in named_obj:
  5940. if obj is list:
  5941. self.on_rename_object(text)
  5942. else:
  5943. try:
  5944. obj.options['name'] = text
  5945. except Exception as e:
  5946. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5947. def convert_any2geo(self):
  5948. self.report_usage("convert_any2geo()")
  5949. def initialize(obj_init, app):
  5950. obj_init.solid_geometry = obj.solid_geometry
  5951. try:
  5952. obj_init.follow_geometry = obj.follow_geometry
  5953. except AttributeError:
  5954. pass
  5955. try:
  5956. obj_init.apertures = obj.apertures
  5957. except AttributeError:
  5958. pass
  5959. try:
  5960. if obj.tools:
  5961. obj_init.tools = obj.tools
  5962. except AttributeError:
  5963. pass
  5964. def initialize_excellon(obj_init, app):
  5965. # objs = self.collection.get_selected()
  5966. # FlatCAMGeometry.merge(objs, obj)
  5967. solid_geo = []
  5968. for tool in obj.tools:
  5969. for geo in obj.tools[tool]['solid_geometry']:
  5970. solid_geo.append(geo)
  5971. obj_init.solid_geometry = deepcopy(solid_geo)
  5972. if not self.collection.get_selected():
  5973. log.warning("App.convert_any2geo --> No object selected")
  5974. self.inform.emit('[WARNING_NOTCL] %s' %
  5975. _("No object is selected. Select an object and try again."))
  5976. return
  5977. for obj in self.collection.get_selected():
  5978. obj_name = obj.options["name"]
  5979. try:
  5980. if isinstance(obj, FlatCAMExcellon):
  5981. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5982. else:
  5983. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5984. except Exception as e:
  5985. return "Operation failed: %s" % str(e)
  5986. def convert_any2gerber(self):
  5987. self.report_usage("convert_any2gerber()")
  5988. def initialize_geometry(obj_init, app):
  5989. apertures = {}
  5990. apid = 0
  5991. apertures[str(apid)] = {}
  5992. apertures[str(apid)]['geometry'] = []
  5993. for obj_orig in obj.solid_geometry:
  5994. new_elem = dict()
  5995. new_elem['solid'] = obj_orig
  5996. new_elem['follow'] = obj_orig.exterior
  5997. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5998. apertures[str(apid)]['size'] = 0.0
  5999. apertures[str(apid)]['type'] = 'C'
  6000. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6001. obj_init.apertures = deepcopy(apertures)
  6002. def initialize_excellon(obj_init, app):
  6003. apertures = {}
  6004. apid = 10
  6005. for tool in obj.tools:
  6006. apertures[str(apid)] = {}
  6007. apertures[str(apid)]['geometry'] = []
  6008. for geo in obj.tools[tool]['solid_geometry']:
  6009. new_el = dict()
  6010. new_el['solid'] = geo
  6011. new_el['follow'] = geo.exterior
  6012. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6013. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6014. apertures[str(apid)]['type'] = 'C'
  6015. apid += 1
  6016. # create solid_geometry
  6017. solid_geometry = []
  6018. for apid in apertures:
  6019. for geo_el in apertures[apid]['geometry']:
  6020. solid_geometry.append(geo_el['solid'])
  6021. solid_geometry = MultiPolygon(solid_geometry)
  6022. solid_geometry = solid_geometry.buffer(0.0000001)
  6023. obj_init.solid_geometry = deepcopy(solid_geometry)
  6024. obj_init.apertures = deepcopy(apertures)
  6025. # clear the working objects (perhaps not necessary due of Python GC)
  6026. apertures.clear()
  6027. if not self.collection.get_selected():
  6028. log.warning("App.convert_any2gerber --> No object selected")
  6029. self.inform.emit('[WARNING_NOTCL] %s' %
  6030. _("No object is selected. Select an object and try again."))
  6031. return
  6032. for obj in self.collection.get_selected():
  6033. obj_name = obj.options["name"]
  6034. try:
  6035. if isinstance(obj, FlatCAMExcellon):
  6036. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6037. elif isinstance(obj, FlatCAMGeometry):
  6038. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6039. else:
  6040. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6041. except Exception as e:
  6042. return "Operation failed: %s" % str(e)
  6043. def abort_all_tasks(self):
  6044. if self.abort_flag is False:
  6045. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6046. self.abort_flag = True
  6047. def app_is_idle(self):
  6048. if self.abort_flag:
  6049. self.inform.emit('[WARNING_NOTCL] %s' %
  6050. _("The current task was gracefully closed on user request..."))
  6051. self.abort_flag = False
  6052. def on_selectall(self):
  6053. self.report_usage("on_selectall()")
  6054. # delete the possible selection box around a possible selected object
  6055. self.delete_selection_shape()
  6056. for name in self.collection.get_names():
  6057. self.collection.set_active(name)
  6058. curr_sel_obj = self.collection.get_by_name(name)
  6059. # create the selection box around the selected object
  6060. if self.defaults['global_selection_shape'] is True:
  6061. self.draw_selection_shape(curr_sel_obj)
  6062. def on_preferences(self):
  6063. # add the tab if it was closed
  6064. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6065. # delete the absolute and relative position and messages in the infobar
  6066. self.ui.position_label.setText("")
  6067. self.ui.rel_position_label.setText("")
  6068. # Switch plot_area to preferences page
  6069. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6070. # self.ui.show()
  6071. # detect changes in the preferences
  6072. for idx in range(self.ui.pref_tab_area.count()):
  6073. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6074. try:
  6075. try:
  6076. tb.textEdited.disconnect(self.on_preferences_edited)
  6077. except (TypeError, AttributeError):
  6078. pass
  6079. tb.textEdited.connect(self.on_preferences_edited)
  6080. except AttributeError:
  6081. pass
  6082. try:
  6083. try:
  6084. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6085. except (TypeError, AttributeError):
  6086. pass
  6087. tb.modificationChanged.connect(self.on_preferences_edited)
  6088. except AttributeError:
  6089. pass
  6090. try:
  6091. try:
  6092. tb.toggled.disconnect(self.on_preferences_edited)
  6093. except (TypeError, AttributeError):
  6094. pass
  6095. tb.toggled.connect(self.on_preferences_edited)
  6096. except AttributeError:
  6097. pass
  6098. try:
  6099. try:
  6100. tb.valueChanged.disconnect(self.on_preferences_edited)
  6101. except (TypeError, AttributeError):
  6102. pass
  6103. tb.valueChanged.connect(self.on_preferences_edited)
  6104. except AttributeError:
  6105. pass
  6106. try:
  6107. try:
  6108. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6109. except (TypeError, AttributeError):
  6110. pass
  6111. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6112. except AttributeError:
  6113. pass
  6114. def on_preferences_edited(self):
  6115. self.inform.emit('[WARNING_NOTCL] %s' %
  6116. _("Preferences edited but not saved."))
  6117. self.preferences_changed_flag = True
  6118. def on_plot_area_tab_closed(self, title):
  6119. if title == _("Preferences"):
  6120. # disconnect
  6121. for idx in range(self.ui.pref_tab_area.count()):
  6122. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6123. try:
  6124. tb.textEdited.disconnect(self.on_preferences_edited)
  6125. except (TypeError, AttributeError):
  6126. pass
  6127. try:
  6128. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6129. except (TypeError, AttributeError):
  6130. pass
  6131. try:
  6132. tb.toggled.disconnect(self.on_preferences_edited)
  6133. except (TypeError, AttributeError):
  6134. pass
  6135. try:
  6136. tb.valueChanged.disconnect(self.on_preferences_edited)
  6137. except (TypeError, AttributeError):
  6138. pass
  6139. try:
  6140. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6141. except (TypeError, AttributeError):
  6142. pass
  6143. if self.preferences_changed_flag is True:
  6144. msgbox = QtWidgets.QMessageBox()
  6145. msgbox.setText(_("One or more values are changed.\n"
  6146. "Do you want to save the Preferences?"))
  6147. msgbox.setWindowTitle(_("Save Preferences"))
  6148. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6149. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6150. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6151. msgbox.setDefaultButton(bt_yes)
  6152. msgbox.exec_()
  6153. response = msgbox.clickedButton()
  6154. if response == bt_yes:
  6155. self.on_save_button()
  6156. self.inform.emit('[success] %s' %
  6157. _("Preferences saved."))
  6158. else:
  6159. self.preferences_changed_flag = False
  6160. return
  6161. if title == _("Code Editor"):
  6162. self.toggle_codeeditor = False
  6163. def on_flipy(self):
  6164. self.report_usage("on_flipy()")
  6165. obj_list = self.collection.get_selected()
  6166. xminlist = []
  6167. yminlist = []
  6168. xmaxlist = []
  6169. ymaxlist = []
  6170. if not obj_list:
  6171. self.inform.emit('[WARNING_NOTCL] %s' %
  6172. _("No object selected to Flip on Y axis."))
  6173. else:
  6174. try:
  6175. # first get a bounding box to fit all
  6176. for obj in obj_list:
  6177. xmin, ymin, xmax, ymax = obj.bounds()
  6178. xminlist.append(xmin)
  6179. yminlist.append(ymin)
  6180. xmaxlist.append(xmax)
  6181. ymaxlist.append(ymax)
  6182. # get the minimum x,y and maximum x,y for all objects selected
  6183. xminimal = min(xminlist)
  6184. yminimal = min(yminlist)
  6185. xmaximal = max(xmaxlist)
  6186. ymaximal = max(ymaxlist)
  6187. px = 0.5 * (xminimal + xmaximal)
  6188. py = 0.5 * (yminimal + ymaximal)
  6189. # execute mirroring
  6190. for obj in obj_list:
  6191. obj.mirror('X', [px, py])
  6192. obj.plot()
  6193. self.object_changed.emit(obj)
  6194. self.inform.emit('[success] %s' %
  6195. _("Flip on Y axis done."))
  6196. except Exception as e:
  6197. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6198. (_("Flip action was not executed."), str(e)))
  6199. return
  6200. def on_flipx(self):
  6201. self.report_usage("on_flipx()")
  6202. obj_list = self.collection.get_selected()
  6203. xminlist = []
  6204. yminlist = []
  6205. xmaxlist = []
  6206. ymaxlist = []
  6207. if not obj_list:
  6208. self.inform.emit('[WARNING_NOTCL] %s' %
  6209. _("No object selected to Flip on X axis."))
  6210. else:
  6211. try:
  6212. # first get a bounding box to fit all
  6213. for obj in obj_list:
  6214. xmin, ymin, xmax, ymax = obj.bounds()
  6215. xminlist.append(xmin)
  6216. yminlist.append(ymin)
  6217. xmaxlist.append(xmax)
  6218. ymaxlist.append(ymax)
  6219. # get the minimum x,y and maximum x,y for all objects selected
  6220. xminimal = min(xminlist)
  6221. yminimal = min(yminlist)
  6222. xmaximal = max(xmaxlist)
  6223. ymaximal = max(ymaxlist)
  6224. px = 0.5 * (xminimal + xmaximal)
  6225. py = 0.5 * (yminimal + ymaximal)
  6226. # execute mirroring
  6227. for obj in obj_list:
  6228. obj.mirror('Y', [px, py])
  6229. obj.plot()
  6230. self.object_changed.emit(obj)
  6231. self.inform.emit('[success] %s' %
  6232. _("Flip on X axis done."))
  6233. except Exception as e:
  6234. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6235. (_("Flip action was not executed."), str(e)))
  6236. return
  6237. def on_rotate(self, silent=False, preset=None):
  6238. self.report_usage("on_rotate()")
  6239. obj_list = self.collection.get_selected()
  6240. xminlist = []
  6241. yminlist = []
  6242. xmaxlist = []
  6243. ymaxlist = []
  6244. if not obj_list:
  6245. self.inform.emit('[WARNING_NOTCL] %s' %
  6246. _("No object selected to Rotate."))
  6247. else:
  6248. if silent is False:
  6249. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6250. min=-360, max=360, decimals=4,
  6251. init_val=float(self.defaults['tools_transform_rotate']))
  6252. num, ok = rotatebox.get_value()
  6253. else:
  6254. num = preset
  6255. ok = True
  6256. if ok:
  6257. try:
  6258. # first get a bounding box to fit all
  6259. for obj in obj_list:
  6260. xmin, ymin, xmax, ymax = obj.bounds()
  6261. xminlist.append(xmin)
  6262. yminlist.append(ymin)
  6263. xmaxlist.append(xmax)
  6264. ymaxlist.append(ymax)
  6265. # get the minimum x,y and maximum x,y for all objects selected
  6266. xminimal = min(xminlist)
  6267. yminimal = min(yminlist)
  6268. xmaximal = max(xmaxlist)
  6269. ymaximal = max(ymaxlist)
  6270. px = 0.5 * (xminimal + xmaximal)
  6271. py = 0.5 * (yminimal + ymaximal)
  6272. for sel_obj in obj_list:
  6273. sel_obj.rotate(-float(num), point=(px, py))
  6274. sel_obj.plot()
  6275. self.object_changed.emit(sel_obj)
  6276. self.inform.emit('[success] %s' %
  6277. _("Rotation done."))
  6278. except Exception as e:
  6279. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6280. (_("Rotation movement was not executed."), str(e)))
  6281. return
  6282. def on_skewx(self):
  6283. self.report_usage("on_skewx()")
  6284. obj_list = self.collection.get_selected()
  6285. xminlist = []
  6286. yminlist = []
  6287. if not obj_list:
  6288. self.inform.emit('[WARNING_NOTCL] %s' %
  6289. _("No object selected to Skew/Shear on X axis."))
  6290. else:
  6291. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6292. min=-360, max=360, decimals=4,
  6293. init_val=float(self.defaults['tools_transform_skew_x']))
  6294. num, ok = skewxbox.get_value()
  6295. if ok:
  6296. # first get a bounding box to fit all
  6297. for obj in obj_list:
  6298. xmin, ymin, xmax, ymax = obj.bounds()
  6299. xminlist.append(xmin)
  6300. yminlist.append(ymin)
  6301. # get the minimum x,y and maximum x,y for all objects selected
  6302. xminimal = min(xminlist)
  6303. yminimal = min(yminlist)
  6304. for obj in obj_list:
  6305. obj.skew(num, 0, point=(xminimal, yminimal))
  6306. obj.plot()
  6307. self.object_changed.emit(obj)
  6308. self.inform.emit('[success] %s' %
  6309. _("Skew on X axis done."))
  6310. def on_skewy(self):
  6311. self.report_usage("on_skewy()")
  6312. obj_list = self.collection.get_selected()
  6313. xminlist = []
  6314. yminlist = []
  6315. if not obj_list:
  6316. self.inform.emit('[WARNING_NOTCL] %s' %
  6317. _("No object selected to Skew/Shear on Y axis."))
  6318. else:
  6319. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6320. min=-360, max=360, decimals=4,
  6321. init_val=float(self.defaults['tools_transform_skew_y']))
  6322. num, ok = skewybox.get_value()
  6323. if ok:
  6324. # first get a bounding box to fit all
  6325. for obj in obj_list:
  6326. xmin, ymin, xmax, ymax = obj.bounds()
  6327. xminlist.append(xmin)
  6328. yminlist.append(ymin)
  6329. # get the minimum x,y and maximum x,y for all objects selected
  6330. xminimal = min(xminlist)
  6331. yminimal = min(yminlist)
  6332. for obj in obj_list:
  6333. obj.skew(0, num, point=(xminimal, yminimal))
  6334. obj.plot()
  6335. self.object_changed.emit(obj)
  6336. self.inform.emit('[success] %s' %
  6337. _("Skew on Y axis done."))
  6338. def on_plots_updated(self):
  6339. """
  6340. Callback used to report when the plots have changed.
  6341. Adjust axes and zooms to fit.
  6342. :return: None
  6343. """
  6344. if self.is_legacy is False:
  6345. self.plotcanvas.update() # TODO: Need update canvas?
  6346. else:
  6347. self.plotcanvas.auto_adjust_axes()
  6348. self.on_zoom_fit(None)
  6349. self.collection.update_view()
  6350. # self.inform.emit(_("Plots updated ..."))
  6351. # TODO: Rework toolbar 'clear', 'replot' functions
  6352. def on_toolbar_replot(self):
  6353. """
  6354. Callback for toolbar button. Re-plots all objects.
  6355. :return: None
  6356. """
  6357. self.report_usage("on_toolbar_replot")
  6358. self.log.debug("on_toolbar_replot()")
  6359. try:
  6360. self.collection.get_active().read_form()
  6361. except AttributeError:
  6362. self.log.debug("on_toolbar_replot(): AttributeError")
  6363. pass
  6364. self.plot_all()
  6365. def on_row_activated(self, index):
  6366. if index.isValid():
  6367. if index.internalPointer().parent_item != self.collection.root_item:
  6368. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6369. self.collection.on_item_activated(index)
  6370. def on_collection_updated(self, obj, state, old_name):
  6371. """
  6372. Create a menu from the object loaded in the collection.
  6373. TODO: should use the collection model to do this
  6374. :param obj: object that was changd (added, deleted, renamed)
  6375. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6376. :param old_name: the old name of the object before the action that triggered this slot happened
  6377. :return: None
  6378. """
  6379. icon_files = {
  6380. "gerber": "share/flatcam_icon16.png",
  6381. "excellon": "share/drill16.png",
  6382. "cncjob": "share/cnc16.png",
  6383. "geometry": "share/geometry16.png",
  6384. "script": "share/script_new16.png",
  6385. "document": "share/notes16_1.png"
  6386. }
  6387. if state == 'append':
  6388. for act in self.ui.menuobjects.actions():
  6389. try:
  6390. act.triggered.disconnect()
  6391. except TypeError:
  6392. pass
  6393. self.ui.menuobjects.clear()
  6394. gerber_list = list()
  6395. exc_list = list()
  6396. cncjob_list = list()
  6397. geo_list = list()
  6398. script_list = list()
  6399. doc_list = list()
  6400. for name in self.collection.get_names():
  6401. obj_named = self.collection.get_by_name(name)
  6402. if obj_named.kind == 'gerber':
  6403. gerber_list.append(name)
  6404. elif obj_named.kind == 'excellon':
  6405. exc_list.append(name)
  6406. elif obj_named.kind == 'cncjob':
  6407. cncjob_list.append(name)
  6408. elif obj_named.kind == 'geometry':
  6409. geo_list.append(name)
  6410. elif obj_named.kind == 'script':
  6411. script_list.append(name)
  6412. elif obj_named.kind == 'document':
  6413. doc_list.append(name)
  6414. def add_act(name):
  6415. obj_for_icon = self.collection.get_by_name(name)
  6416. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6417. add_action.setText(name)
  6418. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6419. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(name))
  6420. self.ui.menuobjects.addAction(add_action)
  6421. for name in gerber_list:
  6422. add_act(name)
  6423. self.ui.menuobjects.addSeparator()
  6424. for name in exc_list:
  6425. add_act(name)
  6426. self.ui.menuobjects.addSeparator()
  6427. for name in cncjob_list:
  6428. add_act(name)
  6429. self.ui.menuobjects.addSeparator()
  6430. for name in geo_list:
  6431. add_act(name)
  6432. self.ui.menuobjects.addSeparator()
  6433. for name in script_list:
  6434. add_act(name)
  6435. self.ui.menuobjects.addSeparator()
  6436. for name in doc_list:
  6437. add_act(name)
  6438. elif state == 'delete':
  6439. for act in self.ui.menuobjects.actions():
  6440. if act.text() == obj.options['name']:
  6441. try:
  6442. act.triggered.disconnect()
  6443. except TypeError:
  6444. pass
  6445. self.ui.menuobjects.removeAction(act)
  6446. break
  6447. elif state == 'rename':
  6448. for act in self.ui.menuobjects.actions():
  6449. if act.text() == old_name:
  6450. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6451. add_action.setText(obj.options['name'])
  6452. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6453. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(obj.options['name']))
  6454. self.ui.menuobjects.insertAction(act, add_action)
  6455. try:
  6456. act.triggered.disconnect()
  6457. except TypeError:
  6458. pass
  6459. self.ui.menuobjects.removeAction(act)
  6460. break
  6461. elif state =='delete_all':
  6462. for act in self.ui.menuobjects.actions():
  6463. try:
  6464. act.triggered.disconnect()
  6465. except TypeError:
  6466. pass
  6467. self.ui.menuobjects.clear()
  6468. def grid_status(self):
  6469. if self.ui.grid_snap_btn.isChecked():
  6470. return True
  6471. else:
  6472. return False
  6473. def populate_cmenu_grids(self):
  6474. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6475. self.ui.cmenu_gridmenu.clear()
  6476. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6477. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6478. grid_toggle.setCheckable(True)
  6479. if self.grid_status() == True:
  6480. grid_toggle.setChecked(True)
  6481. else:
  6482. grid_toggle.setChecked(False)
  6483. self.ui.cmenu_gridmenu.addSeparator()
  6484. for grid in sorted_list:
  6485. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6486. action.triggered.connect(self.set_grid)
  6487. self.ui.cmenu_gridmenu.addSeparator()
  6488. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6489. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6490. grid_add.triggered.connect(self.on_grid_add)
  6491. grid_delete.triggered.connect(self.on_grid_delete)
  6492. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6493. def set_grid(self):
  6494. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6495. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6496. def on_grid_add(self):
  6497. # ## Current application units in lower Case
  6498. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6499. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6500. text=_('Enter a Grid Value:'),
  6501. min=0.0000, max=99.9999, decimals=4)
  6502. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6503. val, ok = grid_add_popup.get_value()
  6504. if ok:
  6505. if float(val) == 0:
  6506. self.inform.emit('[WARNING_NOTCL] %s' %
  6507. _("Please enter a grid value with non-zero value, in Float format."))
  6508. return
  6509. else:
  6510. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6511. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6512. self.inform.emit('[success] %s...' %
  6513. _("New Grid added"))
  6514. else:
  6515. self.inform.emit('[WARNING_NOTCL] %s...' %
  6516. _("Grid already exists"))
  6517. else:
  6518. self.inform.emit('[WARNING_NOTCL] %s...' %
  6519. _("Adding New Grid cancelled"))
  6520. def on_grid_delete(self):
  6521. # ## Current application units in lower Case
  6522. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6523. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6524. text='Enter a Grid Value:',
  6525. min=0.0000, max=99.9999, decimals=4)
  6526. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6527. val, ok = grid_del_popup.get_value()
  6528. if ok:
  6529. if float(val) == 0:
  6530. self.inform.emit('[WARNING_NOTCL] %s' %
  6531. _("Please enter a grid value with non-zero value, in Float format."))
  6532. return
  6533. else:
  6534. try:
  6535. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6536. except ValueError:
  6537. self.inform.emit('[ERROR_NOTCL]%s...' %
  6538. _(" Grid Value does not exist"))
  6539. return
  6540. self.inform.emit('[success] %s...' %
  6541. _("Grid Value deleted"))
  6542. else:
  6543. self.inform.emit('[WARNING_NOTCL] %s...' %
  6544. _("Delete Grid value cancelled"))
  6545. def on_shortcut_list(self):
  6546. self.report_usage("on_shortcut_list()")
  6547. # add the tab if it was closed
  6548. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6549. # delete the absolute and relative position and messages in the infobar
  6550. self.ui.position_label.setText("")
  6551. self.ui.rel_position_label.setText("")
  6552. # Switch plot_area to preferences page
  6553. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6554. # self.ui.show()
  6555. def on_select_tab(self, name):
  6556. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6557. if self.ui.splitter.sizes()[0] == 0:
  6558. self.ui.splitter.setSizes([1, 1])
  6559. else:
  6560. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6561. self.ui.splitter.setSizes([0, 1])
  6562. if name == 'project':
  6563. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6564. elif name == 'selected':
  6565. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6566. elif name == 'tool':
  6567. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6568. def on_copy_name(self):
  6569. self.report_usage("on_copy_name()")
  6570. obj = self.collection.get_active()
  6571. try:
  6572. name = obj.options["name"]
  6573. except AttributeError:
  6574. log.debug("on_copy_name() --> No object selected to copy it's name")
  6575. self.inform.emit('[WARNING_NOTCL]%s' %
  6576. _(" No object selected to copy it's name"))
  6577. return
  6578. self.clipboard.setText(name)
  6579. self.inform.emit(_("Name copied on clipboard ..."))
  6580. def on_mouse_click_over_plot(self, event):
  6581. """
  6582. Default actions are:
  6583. :param event: Contains information about the event, like which button
  6584. was clicked, the pixel coordinates and the axes coordinates.
  6585. :return: None
  6586. """
  6587. self.pos = []
  6588. if self.is_legacy is False:
  6589. event_pos = event.pos
  6590. if self.defaults["global_pan_button"] == '2':
  6591. pan_button = 2
  6592. else:
  6593. pan_button = 3
  6594. # Set the mouse button for panning
  6595. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6596. else:
  6597. event_pos = (event.xdata, event.ydata)
  6598. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6599. if self.defaults["global_pan_button"] == '2':
  6600. pan_button = 3
  6601. else:
  6602. pan_button = 2
  6603. # So it can receive key presses
  6604. self.plotcanvas.native.setFocus()
  6605. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6606. if self.grid_status() == True:
  6607. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6608. else:
  6609. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6610. try:
  6611. if event.button == 1:
  6612. # Reset here the relative coordinates so there is a new reference on the click position
  6613. if self.rel_point1 is None:
  6614. self.rel_point1 = self.pos
  6615. else:
  6616. self.rel_point2 = copy(self.rel_point1)
  6617. self.rel_point1 = self.pos
  6618. self.on_mouse_move_over_plot(event, origin_click=True)
  6619. except Exception as e:
  6620. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6621. def on_double_click_over_plot(self, event):
  6622. if event.button == 1:
  6623. self.doubleclick = True
  6624. def on_mouse_move_over_plot(self, event, origin_click=None):
  6625. """
  6626. Callback for the mouse motion event over the plot.
  6627. :param event: Contains information about the event.
  6628. :param origin_click
  6629. :return: None
  6630. """
  6631. if self.is_legacy is False:
  6632. event_pos = event.pos
  6633. if self.defaults["global_pan_button"] == '2':
  6634. pan_button = 2
  6635. else:
  6636. pan_button = 3
  6637. event_is_dragging = event.is_dragging
  6638. else:
  6639. event_pos = (event.xdata, event.ydata)
  6640. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6641. if self.defaults["global_pan_button"] == '2':
  6642. pan_button = 3
  6643. else:
  6644. pan_button = 2
  6645. event_is_dragging = self.plotcanvas.is_dragging
  6646. # So it can receive key presses
  6647. self.plotcanvas.native.setFocus()
  6648. self.pos_jump = event_pos
  6649. self.ui.popMenu.mouse_is_panning = False
  6650. if not origin_click:
  6651. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6652. if event.button == pan_button and event_is_dragging == 1:
  6653. self.ui.popMenu.mouse_is_panning = True
  6654. return
  6655. if self.rel_point1 is not None:
  6656. try: # May fail in case mouse not within axes
  6657. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6658. if self.grid_status() == True:
  6659. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6660. # Update cursor
  6661. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6662. symbol='++', edge_color=self.cursor_color_3D,
  6663. size=self.defaults["global_cursor_size"])
  6664. else:
  6665. pos = (pos_canvas[0], pos_canvas[1])
  6666. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6667. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6668. dx = pos[0] - float(self.rel_point1[0])
  6669. dy = pos[1] - float(self.rel_point1[1])
  6670. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6671. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6672. self.mouse = [pos[0], pos[1]]
  6673. # if the mouse is moved and the LMB is clicked then the action is a selection
  6674. if event_is_dragging == 1 and event.button == 1:
  6675. self.delete_selection_shape()
  6676. if dx < 0:
  6677. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6678. face_color=self.defaults['global_alt_sel_fill'])
  6679. self.selection_type = False
  6680. elif dx > 0:
  6681. self.draw_moving_selection_shape(self.pos, pos)
  6682. self.selection_type = True
  6683. else:
  6684. self.selection_type = None
  6685. # hover effect - enabled in Preferences -> General -> GUI Settings
  6686. if self.defaults['global_hover']:
  6687. for obj in self.collection.get_list():
  6688. try:
  6689. # select the object(s) only if it is enabled (plotted)
  6690. if obj.options['plot']:
  6691. if obj not in self.collection.get_selected():
  6692. poly_obj = Polygon(
  6693. [(obj.options['xmin'], obj.options['ymin']),
  6694. (obj.options['xmax'], obj.options['ymin']),
  6695. (obj.options['xmax'], obj.options['ymax']),
  6696. (obj.options['xmin'], obj.options['ymax'])]
  6697. )
  6698. if Point(pos).within(poly_obj):
  6699. if obj.isHovering is False:
  6700. obj.isHovering = True
  6701. obj.notHovering = True
  6702. # create the selection box around the selected object
  6703. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6704. else:
  6705. if obj.notHovering is True:
  6706. obj.notHovering = False
  6707. obj.isHovering = False
  6708. self.delete_hover_shape()
  6709. except:
  6710. # the Exception here will happen if we try to select on screen and we have an
  6711. # newly (and empty) just created Geometry or Excellon object that do not have the
  6712. # xmin, xmax, ymin, ymax options.
  6713. # In this case poly_obj creation (see above) will fail
  6714. pass
  6715. except:
  6716. self.ui.position_label.setText("")
  6717. self.ui.rel_position_label.setText("")
  6718. self.mouse = None
  6719. def on_mouse_click_release_over_plot(self, event):
  6720. """
  6721. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6722. and has been registered in ''self.__init__()''.
  6723. :param event: contains information about the event.
  6724. :return:
  6725. """
  6726. pos = 0, 0
  6727. if self.is_legacy is False:
  6728. event_pos = event.pos
  6729. right_button = 2
  6730. else:
  6731. event_pos = (event.xdata, event.ydata)
  6732. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6733. right_button = 3
  6734. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6735. if self.grid_status() == True:
  6736. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6737. else:
  6738. pos = (pos_canvas[0], pos_canvas[1])
  6739. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6740. # canvas menu
  6741. if event.button == right_button: # right click
  6742. if self.ui.popMenu.mouse_is_panning is False:
  6743. self.cursor = QtGui.QCursor()
  6744. self.populate_cmenu_grids()
  6745. self.ui.popMenu.popup(self.cursor.pos())
  6746. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6747. # selection and then select a type of selection ("enclosing" or "touching")
  6748. try:
  6749. if event.button == 1: # left click
  6750. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6751. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6752. if modifiers == QtCore.Qt.ShiftModifier:
  6753. # do not auto open the Project Tab
  6754. self.click_noproject = True
  6755. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6756. self.inform.emit('[success] %s' %
  6757. _("Coordinates copied to clipboard."))
  6758. return
  6759. if self.doubleclick is True:
  6760. self.doubleclick = False
  6761. if self.collection.get_selected():
  6762. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6763. if self.ui.splitter.sizes()[0] == 0:
  6764. self.ui.splitter.setSizes([1, 1])
  6765. # delete the selection shape(S) as it may be in the way
  6766. self.delete_selection_shape()
  6767. self.delete_hover_shape()
  6768. else:
  6769. if self.selection_type is not None:
  6770. self.selection_area_handler(self.pos, pos, self.selection_type)
  6771. self.selection_type = None
  6772. else:
  6773. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6774. if key_modifier == QtCore.Qt.ShiftModifier:
  6775. mod_key = 'Shift'
  6776. elif key_modifier == QtCore.Qt.ControlModifier:
  6777. mod_key = 'Control'
  6778. else:
  6779. mod_key = None
  6780. if mod_key == self.defaults["global_mselect_key"]:
  6781. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6782. # deselect, and if it's not selected then it will be selected
  6783. # If there is no active command (self.command_active is None) then we check if we clicked
  6784. # on a object by checking the bounding limits against mouse click position
  6785. if self.command_active is None:
  6786. self.select_objects(key='CTRL')
  6787. self.delete_hover_shape()
  6788. else:
  6789. # If there is no active command (self.command_active is None) then we check if we clicked
  6790. # on a object by checking the bounding limits against mouse click position
  6791. if self.command_active is None:
  6792. self.select_objects()
  6793. self.delete_hover_shape()
  6794. except Exception as e:
  6795. log.warning("Error: %s" % str(e))
  6796. return
  6797. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6798. """
  6799. :param start_pos: mouse position when the selection LMB click was done
  6800. :param end_pos: mouse position when the left mouse button is released
  6801. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6802. :return:
  6803. """
  6804. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6805. self.delete_selection_shape()
  6806. for obj in self.collection.get_list():
  6807. try:
  6808. # select the object(s) only if it is enabled (plotted)
  6809. if obj.options['plot']:
  6810. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6811. (obj.options['xmax'], obj.options['ymin']),
  6812. (obj.options['xmax'], obj.options['ymax']),
  6813. (obj.options['xmin'], obj.options['ymax'])])
  6814. if sel_type is True:
  6815. if poly_obj.within(poly_selection):
  6816. # create the selection box around the selected object
  6817. if self.defaults['global_selection_shape'] is True:
  6818. self.draw_selection_shape(obj)
  6819. self.collection.set_active(obj.options['name'])
  6820. else:
  6821. if poly_selection.intersects(poly_obj):
  6822. # create the selection box around the selected object
  6823. if self.defaults['global_selection_shape'] is True:
  6824. self.draw_selection_shape(obj)
  6825. self.collection.set_active(obj.options['name'])
  6826. except Exception as e:
  6827. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6828. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6829. # In this case poly_obj creation (see above) will fail
  6830. log.debug("App.selection_area_handler() --> %s" % str(e))
  6831. def select_objects(self, key=None):
  6832. # list where we store the overlapped objects under our mouse left click position
  6833. objects_under_the_click_list = []
  6834. # Populate the list with the overlapped objects on the click position
  6835. curr_x, curr_y = self.pos
  6836. for obj in self.all_objects_list:
  6837. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6838. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6839. if obj.options['name'] not in objects_under_the_click_list:
  6840. if obj.options['plot']:
  6841. # add objects to the objects_under_the_click list only if the object is plotted
  6842. # (active and not disabled)
  6843. objects_under_the_click_list.append(obj.options['name'])
  6844. try:
  6845. # If there is no element in the overlapped objects list then make everyone inactive
  6846. # because we selected "nothing"
  6847. if not objects_under_the_click_list:
  6848. self.collection.set_all_inactive()
  6849. # delete the possible selection box around a possible selected object
  6850. self.delete_selection_shape()
  6851. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6852. # only when working on App
  6853. if self.call_source == 'app':
  6854. if self.click_noproject is False:
  6855. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6856. else:
  6857. # restore auto open the Project Tab
  6858. self.click_noproject = False
  6859. # delete any text in the status bar, implicitly the last object name that was selected
  6860. self.inform.emit("")
  6861. else:
  6862. self.call_source = 'app'
  6863. else:
  6864. # case when there is only an object under the click and we toggle it
  6865. if len(objects_under_the_click_list) == 1:
  6866. if self.collection.get_active() is None:
  6867. self.collection.set_active(objects_under_the_click_list[0])
  6868. # create the selection box around the selected object
  6869. curr_sel_obj = self.collection.get_active()
  6870. if self.defaults['global_selection_shape'] is True:
  6871. self.draw_selection_shape(curr_sel_obj)
  6872. # self.inform.emit('[selected] %s: %s selected' %
  6873. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6874. if curr_sel_obj.kind == 'gerber':
  6875. self.inform.emit(
  6876. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6877. color='green', name=str(curr_sel_obj.options['name'])))
  6878. elif curr_sel_obj.kind == 'excellon':
  6879. self.inform.emit(
  6880. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6881. color='brown', name=str(curr_sel_obj.options['name'])))
  6882. elif curr_sel_obj.kind == 'cncjob':
  6883. self.inform.emit(
  6884. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6885. color='blue', name=str(curr_sel_obj.options['name'])))
  6886. elif curr_sel_obj.kind == 'geometry':
  6887. self.inform.emit(
  6888. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6889. color='red', name=str(curr_sel_obj.options['name'])))
  6890. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6891. self.collection.set_all_inactive()
  6892. self.delete_selection_shape()
  6893. self.collection.set_active(objects_under_the_click_list[0])
  6894. # create the selection box around the selected object
  6895. curr_sel_obj = self.collection.get_active()
  6896. if self.defaults['global_selection_shape'] is True:
  6897. self.draw_selection_shape(curr_sel_obj)
  6898. # self.inform.emit('[selected] %s: %s selected' %
  6899. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6900. if curr_sel_obj.kind == 'gerber':
  6901. self.inform.emit(
  6902. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6903. color='green', name=str(curr_sel_obj.options['name'])))
  6904. elif curr_sel_obj.kind == 'excellon':
  6905. self.inform.emit(
  6906. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6907. color='brown', name=str(curr_sel_obj.options['name'])))
  6908. elif curr_sel_obj.kind == 'cncjob':
  6909. self.inform.emit(
  6910. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6911. color='blue', name=str(curr_sel_obj.options['name'])))
  6912. elif curr_sel_obj.kind == 'geometry':
  6913. self.inform.emit(
  6914. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6915. color='red', name=str(curr_sel_obj.options['name'])))
  6916. else:
  6917. self.collection.set_all_inactive()
  6918. self.delete_selection_shape()
  6919. if self.call_source == 'app':
  6920. # delete any text in the status bar, implicitly the last object name that was selected
  6921. self.inform.emit("")
  6922. else:
  6923. self.call_source = 'app'
  6924. else:
  6925. # If there is no selected object
  6926. # make active the first element of the overlapped objects list
  6927. if self.collection.get_active() is None:
  6928. self.collection.set_active(objects_under_the_click_list[0])
  6929. name_sel_obj = self.collection.get_active().options['name']
  6930. # In case that there is a selected object but it is not in the overlapped object list
  6931. # make that object inactive and activate the first element in the overlapped object list
  6932. if name_sel_obj not in objects_under_the_click_list:
  6933. self.collection.set_inactive(name_sel_obj)
  6934. name_sel_obj = objects_under_the_click_list[0]
  6935. self.collection.set_active(name_sel_obj)
  6936. else:
  6937. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6938. self.collection.set_all_inactive()
  6939. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6940. len(objects_under_the_click_list)])
  6941. curr_sel_obj = self.collection.get_active()
  6942. # delete the possible selection box around a possible selected object
  6943. self.delete_selection_shape()
  6944. # create the selection box around the selected object
  6945. if self.defaults['global_selection_shape'] is True:
  6946. self.draw_selection_shape(curr_sel_obj)
  6947. # self.inform.emit('[selected] %s: %s selected' %
  6948. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6949. if curr_sel_obj.kind == 'gerber':
  6950. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6951. color='green', name=str(curr_sel_obj.options['name'])))
  6952. elif curr_sel_obj.kind == 'excellon':
  6953. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6954. color='brown', name=str(curr_sel_obj.options['name'])))
  6955. elif curr_sel_obj.kind == 'cncjob':
  6956. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6957. color='blue', name=str(curr_sel_obj.options['name'])))
  6958. elif curr_sel_obj.kind == 'geometry':
  6959. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6960. color='red', name=str(curr_sel_obj.options['name'])))
  6961. # for obj in self.collection.get_list():
  6962. # obj.plot()
  6963. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6964. # TODO: on selected objects change the object colors and do not draw the selection box
  6965. # self.plotcanvas.update() # this updates the canvas
  6966. except Exception as e:
  6967. log.error("[ERROR] Something went bad. %s" % str(e))
  6968. return
  6969. def delete_hover_shape(self):
  6970. self.hover_shapes.clear()
  6971. self.hover_shapes.redraw()
  6972. def draw_hover_shape(self, sel_obj, color=None):
  6973. """
  6974. :param sel_obj: the object for which the hover shape must be drawn
  6975. :return:
  6976. """
  6977. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6978. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6979. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6980. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6981. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6982. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6983. hover_rect = hover_rect.buffer(-0.1)
  6984. hover_rect = hover_rect.buffer(0.2)
  6985. else:
  6986. hover_rect = hover_rect.buffer(-0.00393)
  6987. hover_rect = hover_rect.buffer(0.00787)
  6988. # if color:
  6989. # face = Color(color)
  6990. # face.alpha = 0.2
  6991. # outline = Color(color, alpha=0.8)
  6992. # else:
  6993. # face = Color(self.defaults['global_sel_fill'])
  6994. # face.alpha = 0.2
  6995. # outline = self.defaults['global_sel_line']
  6996. if color:
  6997. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6998. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6999. else:
  7000. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7001. outline = self.defaults['global_sel_line']
  7002. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7003. if self.is_legacy is True:
  7004. self.hover_shapes.redraw()
  7005. def delete_selection_shape(self):
  7006. self.move_tool.sel_shapes.clear()
  7007. self.move_tool.sel_shapes.redraw()
  7008. def draw_selection_shape(self, sel_obj, color=None):
  7009. """
  7010. :param sel_obj: the object for which the selection shape must be drawn
  7011. :return:
  7012. """
  7013. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7014. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7015. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7016. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7017. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7018. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7019. sel_rect = sel_rect.buffer(-0.1)
  7020. sel_rect = sel_rect.buffer(0.2)
  7021. else:
  7022. sel_rect = sel_rect.buffer(-0.00393)
  7023. sel_rect = sel_rect.buffer(0.00787)
  7024. # if color:
  7025. # face = Color(color, alpha=0.2)
  7026. # outline = Color(color, alpha=0.8)
  7027. # else:
  7028. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  7029. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  7030. if color:
  7031. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7032. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7033. else:
  7034. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7035. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7036. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7037. color=outline,
  7038. face_color=face,
  7039. update=True,
  7040. layer=0,
  7041. tolerance=None))
  7042. if self.is_legacy is True:
  7043. self.move_tool.sel_shapes.redraw()
  7044. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7045. """
  7046. :param old_coords: old coordinates
  7047. :param coords: new coordinates
  7048. :return:
  7049. """
  7050. if 'color' in kwargs:
  7051. color = kwargs['color']
  7052. else:
  7053. color = self.defaults['global_sel_line']
  7054. if 'face_color' in kwargs:
  7055. face_color = kwargs['face_color']
  7056. else:
  7057. face_color = self.defaults['global_sel_fill']
  7058. if 'face_alpha' in kwargs:
  7059. face_alpha = kwargs['face_alpha']
  7060. else:
  7061. face_alpha = 0.3
  7062. x0, y0 = old_coords
  7063. x1, y1 = coords
  7064. pt1 = (x0, y0)
  7065. pt2 = (x1, y0)
  7066. pt3 = (x1, y1)
  7067. pt4 = (x0, y1)
  7068. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7069. # color_t = Color(face_color)
  7070. # color_t.alpha = face_alpha
  7071. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7072. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7073. layer=0, tolerance=None)
  7074. if self.is_legacy is True:
  7075. self.move_tool.sel_shapes.redraw()
  7076. def on_file_new_click(self):
  7077. if self.collection.get_list() and self.should_we_save:
  7078. msgbox = QtWidgets.QMessageBox()
  7079. # msgbox.setText("<B>Save changes ...</B>")
  7080. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7081. "Creating a New project will delete them.\n"
  7082. "Do you want to Save the project?"))
  7083. msgbox.setWindowTitle(_("Save changes"))
  7084. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7085. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7086. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7087. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7088. msgbox.setDefaultButton(bt_yes)
  7089. msgbox.exec_()
  7090. response = msgbox.clickedButton()
  7091. if response == bt_yes:
  7092. self.on_file_saveprojectas()
  7093. elif response == bt_cancel:
  7094. return
  7095. elif response == bt_no:
  7096. self.on_file_new()
  7097. else:
  7098. self.on_file_new()
  7099. self.inform.emit('[success] %s...' %
  7100. _("New Project created"))
  7101. def on_file_new(self, cli=None):
  7102. """
  7103. Callback for menu item File->New. Returns the application to its
  7104. startup state. This method is thread-safe.
  7105. :return: None
  7106. """
  7107. self.report_usage("on_file_new")
  7108. # Remove everything from memory
  7109. App.log.debug("on_file_new()")
  7110. if self.call_source != 'app':
  7111. self.editor2object(cleanup=True)
  7112. # ## EDITOR section
  7113. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7114. self.exc_editor = FlatCAMExcEditor(self)
  7115. self.grb_editor = FlatCAMGrbEditor(self)
  7116. # Clear pool
  7117. self.clear_pool()
  7118. for obj in self.collection.get_list():
  7119. # delete shapes left drawn from mark shape_collections, if any
  7120. if isinstance(obj, FlatCAMGerber):
  7121. try:
  7122. obj.mark_shapes.enabled = False
  7123. obj.mark_shapes.clear(update=True)
  7124. except AttributeError:
  7125. pass
  7126. # also delete annotation shapes, if any
  7127. elif isinstance(obj, FlatCAMCNCjob):
  7128. try:
  7129. obj.annotation.enabled = False
  7130. obj.annotation.clear(update=True)
  7131. except AttributeError:
  7132. pass
  7133. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7134. self.init_tcl()
  7135. self.delete_selection_shape()
  7136. self.collection.delete_all()
  7137. self.setup_component_editor()
  7138. # Clear project filename
  7139. self.project_filename = None
  7140. # Load the application defaults
  7141. self.load_defaults(filename='current_defaults')
  7142. # Re-fresh project options
  7143. self.on_options_app2project()
  7144. # Init Tools
  7145. self.init_tools()
  7146. if cli is None:
  7147. # Close any Tabs opened in the Plot Tab Area section
  7148. for index in range(self.ui.plot_tab_area.count()):
  7149. self.ui.plot_tab_area.closeTab(index)
  7150. # for whatever reason previous command does not close the last tab so I do it manually
  7151. self.ui.plot_tab_area.closeTab(0)
  7152. # # And then add again the Plot Area
  7153. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7154. self.ui.plot_tab_area.protectTab(0)
  7155. # take the focus of the Notebook on Project Tab.
  7156. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7157. self.set_ui_title(name=_("New Project - Not saved"))
  7158. def obj_properties(self):
  7159. self.report_usage("obj_properties()")
  7160. self.properties_tool.run(toggle=False)
  7161. def on_project_context_save(self):
  7162. obj = self.collection.get_active()
  7163. if type(obj) == FlatCAMGeometry:
  7164. self.on_file_exportdxf()
  7165. elif type(obj) == FlatCAMExcellon:
  7166. self.on_file_saveexcellon()
  7167. elif type(obj) == FlatCAMCNCjob:
  7168. obj.on_exportgcode_button_click()
  7169. elif type(obj) == FlatCAMGerber:
  7170. self.on_file_savegerber()
  7171. elif type(obj) == FlatCAMScript:
  7172. self.on_file_savescript()
  7173. elif type(obj) == FlatCAMDocument:
  7174. self.on_file_savedocument()
  7175. def obj_move(self):
  7176. self.report_usage("obj_move()")
  7177. self.move_tool.run(toggle=False)
  7178. def on_fileopengerber(self, checked=None, name=None):
  7179. """
  7180. File menu callback for opening a Gerber.
  7181. :return: None
  7182. """
  7183. self.report_usage("on_fileopengerber")
  7184. App.log.debug("on_fileopengerber()")
  7185. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7186. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7187. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7188. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7189. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7190. "*.mil);;" \
  7191. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7192. "Allegro Files (*.art);;" \
  7193. "Mentor Files (*.pho *.gdo);;" \
  7194. "All Files (*.*)"
  7195. if name is None:
  7196. try:
  7197. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7198. directory=self.get_last_folder(),
  7199. filter=_filter_)
  7200. except TypeError:
  7201. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7202. filenames = [str(filename) for filename in filenames]
  7203. else:
  7204. filenames = [name]
  7205. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7206. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7207. _("Opening Gerber file.")),
  7208. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7209. color=QtGui.QColor("gray"))
  7210. if len(filenames) == 0:
  7211. self.inform.emit('[WARNING_NOTCL] %s' %
  7212. _("Open Gerber cancelled."))
  7213. else:
  7214. for filename in filenames:
  7215. if filename != '':
  7216. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7217. def on_fileopenexcellon(self, checked=None, name=None):
  7218. """
  7219. File menu callback for opening an Excellon file.
  7220. :return: None
  7221. """
  7222. self.report_usage("on_fileopenexcellon")
  7223. App.log.debug("on_fileopenexcellon()")
  7224. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7225. "All Files (*.*)"
  7226. if name is None:
  7227. try:
  7228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7229. directory=self.get_last_folder(),
  7230. filter=_filter_)
  7231. except TypeError:
  7232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7233. filenames = [str(filename) for filename in filenames]
  7234. else:
  7235. filenames = [str(name)]
  7236. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7237. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7238. _("Opening Excellon file.")),
  7239. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7240. color=QtGui.QColor("gray"))
  7241. if len(filenames) == 0:
  7242. self.inform.emit('[WARNING_NOTCL]%s' %
  7243. _(" Open Excellon cancelled."))
  7244. else:
  7245. for filename in filenames:
  7246. if filename != '':
  7247. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7248. def on_fileopengcode(self, checked=None, name=None):
  7249. """
  7250. File menu call back for opening gcode.
  7251. :return: None
  7252. """
  7253. self.report_usage("on_fileopengcode")
  7254. App.log.debug("on_fileopengcode()")
  7255. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7256. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7257. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7258. "All Files (*.*)"
  7259. if name is None:
  7260. try:
  7261. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7262. directory=self.get_last_folder(),
  7263. filter=_filter_)
  7264. except TypeError:
  7265. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7266. filenames = [str(filename) for filename in filenames]
  7267. else:
  7268. filenames = [name]
  7269. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7270. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7271. _("Opening G-Code file.")),
  7272. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7273. color=QtGui.QColor("gray"))
  7274. if len(filenames) == 0:
  7275. self.inform.emit('[WARNING_NOTCL] %s' %
  7276. _("Open G-Code cancelled."))
  7277. else:
  7278. for filename in filenames:
  7279. if filename != '':
  7280. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7281. def on_file_openproject(self, checked=None):
  7282. """
  7283. File menu callback for opening a project.
  7284. :return: None
  7285. """
  7286. self.report_usage("on_file_openproject")
  7287. App.log.debug("on_file_openproject()")
  7288. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7289. try:
  7290. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7291. directory=self.get_last_folder(), filter=_filter_)
  7292. except TypeError:
  7293. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7294. # The Qt methods above will return a QString which can cause problems later.
  7295. # So far json.dump() will fail to serialize it.
  7296. # TODO: Improve the serialization methods and remove this fix.
  7297. filename = str(filename)
  7298. if filename == "":
  7299. self.inform.emit('[WARNING_NOTCL] %s' %
  7300. _("Open Project cancelled."))
  7301. else:
  7302. # self.worker_task.emit({'fcn': self.open_project,
  7303. # 'params': [filename]})
  7304. # The above was failing because open_project() is not
  7305. # thread safe. The new_project()
  7306. self.open_project(filename)
  7307. def on_file_openconfig(self, checked=None):
  7308. """
  7309. File menu callback for opening a config file.
  7310. :return: None
  7311. """
  7312. self.report_usage("on_file_openconfig")
  7313. App.log.debug("on_file_openconfig()")
  7314. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7315. try:
  7316. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7317. directory=self.data_path, filter=_filter_)
  7318. except TypeError:
  7319. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7320. filter=_filter_)
  7321. if filename == "":
  7322. self.inform.emit('[WARNING_NOTCL] %s' %
  7323. _("Open Config cancelled."))
  7324. else:
  7325. self.open_config_file(filename)
  7326. def on_file_exportsvg(self):
  7327. """
  7328. Callback for menu item File->Export SVG.
  7329. :return: None
  7330. """
  7331. self.report_usage("on_file_exportsvg")
  7332. App.log.debug("on_file_exportsvg()")
  7333. obj = self.collection.get_active()
  7334. if obj is None:
  7335. self.inform.emit('[WARNING_NOTCL] %s' %
  7336. _("No object selected."))
  7337. msg = _("Please Select a Geometry object to export")
  7338. msgbox = QtWidgets.QMessageBox()
  7339. msgbox.setInformativeText(msg)
  7340. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7341. msgbox.setDefaultButton(bt_ok)
  7342. msgbox.exec_()
  7343. return
  7344. # Check for more compatible types and add as required
  7345. if (not isinstance(obj, FlatCAMGeometry)
  7346. and not isinstance(obj, FlatCAMGerber)
  7347. and not isinstance(obj, FlatCAMCNCjob)
  7348. and not isinstance(obj, FlatCAMExcellon)):
  7349. msg = '[ERROR_NOTCL] %s' % \
  7350. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7351. msgbox = QtWidgets.QMessageBox()
  7352. msgbox.setInformativeText(msg)
  7353. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7354. msgbox.setDefaultButton(bt_ok)
  7355. msgbox.exec_()
  7356. return
  7357. name = obj.options["name"]
  7358. _filter = "SVG File (*.svg);;All Files (*.*)"
  7359. try:
  7360. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7361. caption=_("Export SVG"),
  7362. directory=self.get_last_save_folder() + '/' + str(name),
  7363. filter=_filter)
  7364. except TypeError:
  7365. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7366. filename = str(filename)
  7367. if filename == "":
  7368. self.inform.emit('[WARNING_NOTCL]%s' %
  7369. _(" Export SVG cancelled."))
  7370. return
  7371. else:
  7372. self.export_svg(name, filename)
  7373. if self.defaults["global_open_style"] is False:
  7374. self.file_opened.emit("SVG", filename)
  7375. self.file_saved.emit("SVG", filename)
  7376. def on_file_exportpng(self):
  7377. self.report_usage("on_file_exportpng")
  7378. App.log.debug("on_file_exportpng()")
  7379. self.date = str(datetime.today()).rpartition('.')[0]
  7380. self.date = ''.join(c for c in self.date if c not in ':-')
  7381. self.date = self.date.replace(' ', '_')
  7382. image = _screenshot()
  7383. data = np.asarray(image)
  7384. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7385. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7386. _('Data must be a 3D array with last dimension 3 or 4'))
  7387. return
  7388. filter_ = "PNG File (*.png);;All Files (*.*)"
  7389. try:
  7390. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7391. caption=_("Export PNG Image"),
  7392. directory=self.get_last_save_folder() + '/png_' + self.date,
  7393. filter=filter_)
  7394. except TypeError:
  7395. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7396. filename = str(filename)
  7397. if filename == "":
  7398. self.inform.emit(_("Export PNG cancelled."))
  7399. return
  7400. else:
  7401. write_png(filename, data)
  7402. if self.defaults["global_open_style"] is False:
  7403. self.file_opened.emit("png", filename)
  7404. self.file_saved.emit("png", filename)
  7405. def on_file_savegerber(self):
  7406. """
  7407. Callback for menu item in Project context menu.
  7408. :return: None
  7409. """
  7410. self.report_usage("on_file_savegerber")
  7411. App.log.debug("on_file_savegerber()")
  7412. obj = self.collection.get_active()
  7413. if obj is None:
  7414. self.inform.emit('[WARNING_NOTCL] %s' %
  7415. _("No object selected. Please select an Gerber object to export."))
  7416. return
  7417. # Check for more compatible types and add as required
  7418. if not isinstance(obj, FlatCAMGerber):
  7419. self.inform.emit('[ERROR_NOTCL] %s' %
  7420. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7421. return
  7422. name = self.collection.get_active().options["name"]
  7423. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7424. try:
  7425. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7426. caption="Save Gerber source file",
  7427. directory=self.get_last_save_folder() + '/' + name,
  7428. filter=_filter)
  7429. except TypeError:
  7430. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7431. filename = str(filename)
  7432. if filename == "":
  7433. self.inform.emit('[WARNING_NOTCL] %s' %
  7434. _("Save Gerber source file cancelled."))
  7435. return
  7436. else:
  7437. self.save_source_file(name, filename)
  7438. if self.defaults["global_open_style"] is False:
  7439. self.file_opened.emit("Gerber", filename)
  7440. self.file_saved.emit("Gerber", filename)
  7441. def on_file_savescript(self):
  7442. """
  7443. Callback for menu item in Project context menu.
  7444. :return: None
  7445. """
  7446. self.report_usage("on_file_savescript")
  7447. App.log.debug("on_file_savescript()")
  7448. obj = self.collection.get_active()
  7449. if obj is None:
  7450. self.inform.emit('[WARNING_NOTCL] %s' %
  7451. _("No object selected. Please select an Script object to export."))
  7452. return
  7453. # Check for more compatible types and add as required
  7454. if not isinstance(obj, FlatCAMScript):
  7455. self.inform.emit('[ERROR_NOTCL] %s' %
  7456. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7457. return
  7458. name = self.collection.get_active().options["name"]
  7459. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7460. try:
  7461. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7462. caption="Save Script source file",
  7463. directory=self.get_last_save_folder() + '/' + name,
  7464. filter=_filter)
  7465. except TypeError:
  7466. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7467. filename = str(filename)
  7468. if filename == "":
  7469. self.inform.emit('[WARNING_NOTCL] %s' %
  7470. _("Save Script source file cancelled."))
  7471. return
  7472. else:
  7473. self.save_source_file(name, filename)
  7474. if self.defaults["global_open_style"] is False:
  7475. self.file_opened.emit("Script", filename)
  7476. self.file_saved.emit("Script", filename)
  7477. def on_file_savedocument(self):
  7478. """
  7479. Callback for menu item in Project context menu.
  7480. :return: None
  7481. """
  7482. self.report_usage("on_file_savedocument")
  7483. App.log.debug("on_file_savedocument()")
  7484. obj = self.collection.get_active()
  7485. if obj is None:
  7486. self.inform.emit('[WARNING_NOTCL] %s' %
  7487. _("No object selected. Please select an Document object to export."))
  7488. return
  7489. # Check for more compatible types and add as required
  7490. if not isinstance(obj, FlatCAMScript):
  7491. self.inform.emit('[ERROR_NOTCL] %s' %
  7492. _("Failed. Only Document objects can be saved as Document files..."))
  7493. return
  7494. name = self.collection.get_active().options["name"]
  7495. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7496. try:
  7497. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7498. caption="Save Document source file",
  7499. directory=self.get_last_save_folder() + '/' + name,
  7500. filter=_filter)
  7501. except TypeError:
  7502. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7503. filename = str(filename)
  7504. if filename == "":
  7505. self.inform.emit('[WARNING_NOTCL] %s' %
  7506. _("Save Document source file cancelled."))
  7507. return
  7508. else:
  7509. self.save_source_file(name, filename)
  7510. if self.defaults["global_open_style"] is False:
  7511. self.file_opened.emit("Document", filename)
  7512. self.file_saved.emit("Document", filename)
  7513. def on_file_saveexcellon(self):
  7514. """
  7515. Callback for menu item in project context menu.
  7516. :return: None
  7517. """
  7518. self.report_usage("on_file_saveexcellon")
  7519. App.log.debug("on_file_saveexcellon()")
  7520. obj = self.collection.get_active()
  7521. if obj is None:
  7522. self.inform.emit('[WARNING_NOTCL] %s' %
  7523. _("No object selected. Please select an Excellon object to export."))
  7524. return
  7525. # Check for more compatible types and add as required
  7526. if not isinstance(obj, FlatCAMExcellon):
  7527. self.inform.emit('[ERROR_NOTCL] %s' %
  7528. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7529. return
  7530. name = self.collection.get_active().options["name"]
  7531. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7532. try:
  7533. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7534. caption=_("Save Excellon source file"),
  7535. directory=self.get_last_save_folder() + '/' + name,
  7536. filter=_filter)
  7537. except TypeError:
  7538. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7539. filename = str(filename)
  7540. if filename == "":
  7541. self.inform.emit('[WARNING_NOTCL] %s' %
  7542. _("Saving Excellon source file cancelled."))
  7543. return
  7544. else:
  7545. self.save_source_file(name, filename)
  7546. if self.defaults["global_open_style"] is False:
  7547. self.file_opened.emit("Excellon", filename)
  7548. self.file_saved.emit("Excellon", filename)
  7549. def on_file_exportexcellon(self):
  7550. """
  7551. Callback for menu item File->Export->Excellon.
  7552. :return: None
  7553. """
  7554. self.report_usage("on_file_exportexcellon")
  7555. App.log.debug("on_file_exportexcellon()")
  7556. obj = self.collection.get_active()
  7557. if obj is None:
  7558. self.inform.emit('[WARNING_NOTCL] %s' %
  7559. _("No object selected. Please Select an Excellon object to export."))
  7560. return
  7561. # Check for more compatible types and add as required
  7562. if not isinstance(obj, FlatCAMExcellon):
  7563. self.inform.emit('[ERROR_NOTCL] %s' %
  7564. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7565. return
  7566. name = self.collection.get_active().options["name"]
  7567. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7568. try:
  7569. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7570. caption=_("Export Excellon"),
  7571. directory=self.get_last_save_folder() + '/' + name,
  7572. filter=_filter)
  7573. except TypeError:
  7574. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7575. filename = str(filename)
  7576. if filename == "":
  7577. self.inform.emit('[WARNING_NOTCL] %s' %
  7578. _("Export Excellon cancelled."))
  7579. return
  7580. else:
  7581. self.export_excellon(name, filename)
  7582. if self.defaults["global_open_style"] is False:
  7583. self.file_opened.emit("Excellon", filename)
  7584. self.file_saved.emit("Excellon", filename)
  7585. def on_file_exportgerber(self):
  7586. """
  7587. Callback for menu item File->Export->Gerber.
  7588. :return: None
  7589. """
  7590. self.report_usage("on_file_exportgerber")
  7591. App.log.debug("on_file_exportgerber()")
  7592. obj = self.collection.get_active()
  7593. if obj is None:
  7594. self.inform.emit('[WARNING_NOTCL] %s' %
  7595. _("No object selected. Please Select an Gerber object to export."))
  7596. return
  7597. # Check for more compatible types and add as required
  7598. if not isinstance(obj, FlatCAMGerber):
  7599. self.inform.emit('[ERROR_NOTCL] %s' %
  7600. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7601. return
  7602. name = self.collection.get_active().options["name"]
  7603. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7604. try:
  7605. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7606. caption=_("Export Gerber"),
  7607. directory=self.get_last_save_folder() + '/' + name,
  7608. filter=_filter_)
  7609. except TypeError:
  7610. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7611. filename = str(filename)
  7612. if filename == "":
  7613. self.inform.emit('[WARNING_NOTCL] %s' %
  7614. _("Export Gerber cancelled."))
  7615. return
  7616. else:
  7617. self.export_gerber(name, filename)
  7618. if self.defaults["global_open_style"] is False:
  7619. self.file_opened.emit("Gerber", filename)
  7620. self.file_saved.emit("Gerber", filename)
  7621. def on_file_exportdxf(self):
  7622. """
  7623. Callback for menu item File->Export DXF.
  7624. :return: None
  7625. """
  7626. self.report_usage("on_file_exportdxf")
  7627. App.log.debug("on_file_exportdxf()")
  7628. obj = self.collection.get_active()
  7629. if obj is None:
  7630. self.inform.emit('[WARNING_NOTCL] %s' %
  7631. _("No object selected."))
  7632. msg = _("Please Select a Geometry object to export")
  7633. msgbox = QtWidgets.QMessageBox()
  7634. msgbox.setInformativeText(msg)
  7635. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7636. msgbox.setDefaultButton(bt_ok)
  7637. msgbox.exec_()
  7638. return
  7639. # Check for more compatible types and add as required
  7640. if not isinstance(obj, FlatCAMGeometry):
  7641. msg = '[ERROR_NOTCL] %s' % \
  7642. _("Only Geometry objects can be used.")
  7643. msgbox = QtWidgets.QMessageBox()
  7644. msgbox.setInformativeText(msg)
  7645. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7646. msgbox.setDefaultButton(bt_ok)
  7647. msgbox.exec_()
  7648. return
  7649. name = self.collection.get_active().options["name"]
  7650. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7651. try:
  7652. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7653. caption=_("Export DXF"),
  7654. directory=self.get_last_save_folder() + '/' + name,
  7655. filter=_filter_)
  7656. except TypeError:
  7657. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7658. filter=_filter_)
  7659. filename = str(filename)
  7660. if filename == "":
  7661. self.inform.emit('[WARNING_NOTCL] %s' %
  7662. _("Export DXF cancelled."))
  7663. return
  7664. else:
  7665. self.export_dxf(name, filename)
  7666. if self.defaults["global_open_style"] is False:
  7667. self.file_opened.emit("DXF", filename)
  7668. self.file_saved.emit("DXF", filename)
  7669. def on_file_importsvg(self, type_of_obj):
  7670. """
  7671. Callback for menu item File->Import SVG.
  7672. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7673. :type type_of_obj: str
  7674. :return: None
  7675. """
  7676. self.report_usage("on_file_importsvg")
  7677. App.log.debug("on_file_importsvg()")
  7678. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7679. try:
  7680. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7681. directory=self.get_last_folder(), filter=_filter_)
  7682. except TypeError:
  7683. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7684. filter=_filter_)
  7685. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7686. type_of_obj = "geometry"
  7687. filenames = [str(filename) for filename in filenames]
  7688. if len(filenames) == 0:
  7689. self.inform.emit('[WARNING_NOTCL] %s' %
  7690. _("Open SVG cancelled."))
  7691. else:
  7692. for filename in filenames:
  7693. if filename != '':
  7694. self.worker_task.emit({'fcn': self.import_svg,
  7695. 'params': [filename, type_of_obj]})
  7696. def on_file_importdxf(self, type_of_obj):
  7697. """
  7698. Callback for menu item File->Import DXF.
  7699. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7700. :type type_of_obj: str
  7701. :return: None
  7702. """
  7703. self.report_usage("on_file_importdxf")
  7704. App.log.debug("on_file_importdxf()")
  7705. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7706. try:
  7707. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7708. directory=self.get_last_folder(),
  7709. filter=_filter_)
  7710. except TypeError:
  7711. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7712. filter=_filter_)
  7713. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7714. type_of_obj = "geometry"
  7715. filenames = [str(filename) for filename in filenames]
  7716. if len(filenames) == 0:
  7717. self.inform.emit('[WARNING_NOTCL] %s' %
  7718. _("Open DXF cancelled."))
  7719. else:
  7720. for filename in filenames:
  7721. if filename != '':
  7722. self.worker_task.emit({'fcn': self.import_dxf,
  7723. 'params': [filename, type_of_obj]})
  7724. # ###############################################################################################################
  7725. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7726. # ###############################################################################################################
  7727. def init_code_editor(self, name):
  7728. self.text_editor_tab = TextEditor(app=self)
  7729. # add the tab if it was closed
  7730. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  7731. self.text_editor_tab.setObjectName('text_editor_tab')
  7732. # delete the absolute and relative position and messages in the infobar
  7733. self.ui.position_label.setText("")
  7734. self.ui.rel_position_label.setText("")
  7735. # first clear previous text in text editor (if any)
  7736. self.text_editor_tab.code_editor.clear()
  7737. self.text_editor_tab.code_editor.setReadOnly(False)
  7738. self.toggle_codeeditor = True
  7739. self.text_editor_tab.code_editor.completer_enable = False
  7740. self.text_editor_tab.buttonRun.hide()
  7741. # make sure to keep a reference to the code editor
  7742. self.reference_code_editor = self.text_editor_tab.code_editor
  7743. # Switch plot_area to CNCJob tab
  7744. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  7745. def on_view_source(self):
  7746. self.inform.emit('%s' %
  7747. _("Viewing the source code of the selected object."))
  7748. self.proc_container.view.set_busy(_("Loading..."))
  7749. try:
  7750. obj = self.collection.get_active()
  7751. except Exception as e:
  7752. log.debug("App.on_view_source() --> %s" % str(e))
  7753. self.inform.emit('[WARNING_NOTCL] %s' %
  7754. _("Select an Gerber or Excellon file to view it's source file."))
  7755. return 'fail'
  7756. if obj.kind == 'gerber':
  7757. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7758. elif obj.kind == 'excellon':
  7759. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7760. elif obj.kind == 'cncjob':
  7761. "GCode Files (*.NC);;All Files (*.*)"
  7762. else:
  7763. flt = "All Files (*.*)"
  7764. self.source_editor_tab = TextEditor(app=self)
  7765. # add the tab if it was closed
  7766. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7767. self.source_editor_tab.setObjectName('source_editor_tab')
  7768. # delete the absolute and relative position and messages in the infobar
  7769. self.ui.position_label.setText("")
  7770. self.ui.rel_position_label.setText("")
  7771. # first clear previous text in text editor (if any)
  7772. self.source_editor_tab.code_editor.clear()
  7773. self.source_editor_tab.code_editor.setReadOnly(False)
  7774. self.source_editor_tab.code_editor.completer_enable = False
  7775. self.source_editor_tab.buttonRun.hide()
  7776. # Switch plot_area to CNCJob tab
  7777. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7778. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7779. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7780. self.source_editor_tab.buttonSave.clicked.disconnect()
  7781. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7782. # then append the text from GCode to the text editor
  7783. if obj.kind == 'cncjob':
  7784. try:
  7785. file = obj.export_gcode(
  7786. preamble=self.defaults["cncjob_prepend"],
  7787. postamble=self.defaults["cncjob_append"],
  7788. to_file=True)
  7789. if file == 'fail':
  7790. return 'fail'
  7791. except AttributeError:
  7792. self.inform.emit('[WARNING_NOTCL] %s' %
  7793. _("There is no selected object for which to see it's source file code."))
  7794. return 'fail'
  7795. else:
  7796. try:
  7797. file = StringIO(obj.source_file)
  7798. except AttributeError:
  7799. self.inform.emit('[WARNING_NOTCL] %s' %
  7800. _("There is no selected object for which to see it's source file code."))
  7801. return 'fail'
  7802. self.source_editor_tab.t_frame.hide()
  7803. try:
  7804. for line in file:
  7805. QtWidgets.QApplication.processEvents()
  7806. proc_line = str(line).strip('\n')
  7807. self.source_editor_tab.code_editor.append(proc_line)
  7808. except Exception as e:
  7809. log.debug('App.on_view_source() -->%s' % str(e))
  7810. self.inform.emit('[ERROR] %s: %s' %
  7811. (_('Failed to load the source code for the selected object'), str(e)))
  7812. return
  7813. self.source_editor_tab.handleTextChanged()
  7814. self.source_editor_tab.t_frame.show()
  7815. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7816. self.proc_container.view.set_idle()
  7817. # self.ui.show()
  7818. def on_toggle_code_editor(self):
  7819. self.report_usage("on_toggle_code_editor()")
  7820. if self.toggle_codeeditor is False:
  7821. self.init_code_editor(name=_("Code Editor"))
  7822. self.text_editor_tab.buttonOpen.clicked.disconnect()
  7823. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  7824. self.text_editor_tab.buttonSave.clicked.disconnect()
  7825. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  7826. else:
  7827. for idx in range(self.ui.plot_tab_area.count()):
  7828. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7829. self.ui.plot_tab_area.closeTab(idx)
  7830. break
  7831. self.toggle_codeeditor = False
  7832. def on_code_editor_close(self):
  7833. print("closed")
  7834. self.toggle_codeeditor = False
  7835. def on_filenewscript(self, silent=False, name=None, text=None):
  7836. """
  7837. Will create a new script file and open it in the Code Editor
  7838. :param silent: if True will not display status messages
  7839. :return: None
  7840. """
  7841. if silent is False:
  7842. self.inform.emit('[success] %s' %
  7843. _("New TCL script file created in Code Editor."))
  7844. # delete the absolute and relative position and messages in the infobar
  7845. self.ui.position_label.setText("")
  7846. self.ui.rel_position_label.setText("")
  7847. if name is not None:
  7848. self.new_script_object(name=name, text=text)
  7849. else:
  7850. self.new_script_object(text=text)
  7851. # script_text = script_obj.source_file
  7852. #
  7853. # self.proc_container.view.set_busy(_("Loading..."))
  7854. # script_obj.script_editor_tab.t_frame.hide()
  7855. #
  7856. # script_obj.script_editor_tab.t_frame.show()
  7857. # self.proc_container.view.set_idle()
  7858. def on_fileopenscript(self, name=None, silent=False):
  7859. """
  7860. Will open a Tcl script file into the Code Editor
  7861. :param silent: if True will not display status messages
  7862. :param name: name of a Tcl script file to open
  7863. :return:
  7864. """
  7865. self.report_usage("on_fileopenscript")
  7866. App.log.debug("on_fileopenscript()")
  7867. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7868. if name:
  7869. filenames = [name]
  7870. else:
  7871. try:
  7872. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7873. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7874. except TypeError:
  7875. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7876. if len(filenames) == 0:
  7877. if silent is False:
  7878. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  7879. else:
  7880. for filename in filenames:
  7881. if filename != '':
  7882. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7883. def on_filerunscript(self, name=None, silent=False):
  7884. """
  7885. File menu callback for loading and running a TCL script.
  7886. :param silent: if True will not display status messages
  7887. :param name: name of a Tcl script file to be run by FlatCAM
  7888. :return: None
  7889. """
  7890. self.report_usage("on_filerunscript")
  7891. App.log.debug("on_file_runscript()")
  7892. if name:
  7893. filename = name
  7894. if self.cmd_line_headless != 1:
  7895. self.splash.showMessage('%s: %ssec\n%s' %
  7896. (_("Canvas initialization started.\n"
  7897. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7898. _("Executing FlatCAMScript file.")
  7899. ),
  7900. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7901. color=QtGui.QColor("gray"))
  7902. else:
  7903. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7904. try:
  7905. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7906. directory=self.get_last_folder(), filter=_filter_)
  7907. except TypeError:
  7908. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7909. # The Qt methods above will return a QString which can cause problems later.
  7910. # So far json.dump() will fail to serialize it.
  7911. # TODO: Improve the serialization methods and remove this fix.
  7912. filename = str(filename)
  7913. if filename == "":
  7914. if silent is False:
  7915. self.inform.emit('[WARNING_NOTCL] %s' %
  7916. _("Run TCL script cancelled."))
  7917. else:
  7918. if self.cmd_line_headless != 1:
  7919. if self.ui.shell_dock.isHidden():
  7920. self.ui.shell_dock.show()
  7921. try:
  7922. with open(filename, "r") as tcl_script:
  7923. cmd_line_shellfile_content = tcl_script.read()
  7924. if self.cmd_line_headless != 1:
  7925. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7926. else:
  7927. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7928. if silent is False:
  7929. self.inform.emit('[success] %s' %
  7930. _("TCL script file opened in Code Editor and executed."))
  7931. except Exception as e:
  7932. log.debug("App.on_filerunscript() -> %s" % str(e))
  7933. sys.exit(2)
  7934. def on_file_saveproject(self, silent=False):
  7935. """
  7936. Callback for menu item File->Save Project. Saves the project to
  7937. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7938. if set to None. The project is saved by calling ``self.save_project()``.
  7939. :param silent: if True will not display status messages
  7940. :return: None
  7941. """
  7942. self.report_usage("on_file_saveproject")
  7943. if self.project_filename is None:
  7944. self.on_file_saveprojectas()
  7945. else:
  7946. self.worker_task.emit({'fcn': self.save_project,
  7947. 'params': [self.project_filename, silent]})
  7948. if self.defaults["global_open_style"] is False:
  7949. self.file_opened.emit("project", self.project_filename)
  7950. self.file_saved.emit("project", self.project_filename)
  7951. self.set_ui_title(name=self.project_filename)
  7952. self.should_we_save = False
  7953. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7954. """
  7955. Callback for menu item File->Save Project As... Opens a file
  7956. chooser and saves the project to the given file via
  7957. ``self.save_project()``.
  7958. :param make_copy if to be create a copy of the project; boolean
  7959. :param use_thread: if to be run in a separate thread; boolean
  7960. :param quit_action: if to be followed by quiting the application; boolean
  7961. :return: None
  7962. """
  7963. self.report_usage("on_file_saveprojectas")
  7964. self.date = str(datetime.today()).rpartition('.')[0]
  7965. self.date = ''.join(c for c in self.date if c not in ':-')
  7966. self.date = self.date.replace(' ', '_')
  7967. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7968. try:
  7969. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7970. caption=_("Save Project As ..."),
  7971. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7972. filter=filter_)
  7973. except TypeError:
  7974. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7975. filename = str(filename)
  7976. if filename == '':
  7977. self.inform.emit('[WARNING_NOTCL] %s' %
  7978. _("Save Project cancelled."))
  7979. return
  7980. try:
  7981. f = open(filename, 'r')
  7982. f.close()
  7983. except IOError:
  7984. pass
  7985. if use_thread is True:
  7986. self.worker_task.emit({'fcn': self.save_project,
  7987. 'params': [filename, quit_action]})
  7988. else:
  7989. self.save_project(filename, quit_action)
  7990. # self.save_project(filename)
  7991. if self.defaults["global_open_style"] is False:
  7992. self.file_opened.emit("project", filename)
  7993. self.file_saved.emit("project", filename)
  7994. if not make_copy:
  7995. self.project_filename = filename
  7996. self.set_ui_title(name=self.project_filename)
  7997. self.should_we_save = False
  7998. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7999. """
  8000. Exports a Geometry Object to an SVG file.
  8001. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8002. :param filename: Path to the SVG file to save to.
  8003. :param scale_factor: factor by which to change/scale the thickness of the features
  8004. :return:
  8005. """
  8006. self.report_usage("export_svg()")
  8007. if filename is None:
  8008. filename = self.defaults["global_last_save_folder"]
  8009. self.log.debug("export_svg()")
  8010. try:
  8011. obj = self.collection.get_by_name(str(obj_name))
  8012. except:
  8013. # TODO: The return behavior has not been established... should raise exception?
  8014. return "Could not retrieve object: %s" % obj_name
  8015. with self.proc_container.new(_("Exporting SVG")) as proc:
  8016. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8017. # Determine bounding area for svg export
  8018. bounds = obj.bounds()
  8019. size = obj.size()
  8020. # Convert everything to strings for use in the xml doc
  8021. svgwidth = str(size[0])
  8022. svgheight = str(size[1])
  8023. minx = str(bounds[0])
  8024. miny = str(bounds[1] - size[1])
  8025. uom = obj.units.lower()
  8026. # Add a SVG Header and footer to the svg output from shapely
  8027. # The transform flips the Y Axis so that everything renders
  8028. # properly within svg apps such as inkscape
  8029. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8030. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8031. svg_header += 'width="' + svgwidth + uom + '" '
  8032. svg_header += 'height="' + svgheight + uom + '" '
  8033. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8034. svg_header += '<g transform="scale(1,-1)">'
  8035. svg_footer = '</g> </svg>'
  8036. svg_elem = svg_header + exported_svg + svg_footer
  8037. # Parse the xml through a xml parser just to add line feeds
  8038. # and to make it look more pretty for the output
  8039. svgcode = parse_xml_string(svg_elem)
  8040. try:
  8041. with open(filename, 'w') as fp:
  8042. fp.write(svgcode.toprettyxml())
  8043. except PermissionError:
  8044. self.inform.emit('[WARNING] %s' %
  8045. _("Permission denied, saving not possible.\n"
  8046. "Most likely another app is holding the file open and not accessible."))
  8047. return 'fail'
  8048. if self.defaults["global_open_style"] is False:
  8049. self.file_opened.emit("SVG", filename)
  8050. self.file_saved.emit("SVG", filename)
  8051. self.inform.emit('[success] %s: %s' %
  8052. (_("SVG file exported to"), filename))
  8053. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  8054. """
  8055. Exports a Geometry Object to an SVG file in negative.
  8056. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8057. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8058. :param filename: Path to the SVG file to save to.
  8059. :param boundary: thickness of a black border to surround all the features
  8060. :param scale_factor: factor by which to change/scale the thickness of the features
  8061. :param use_thread: if to be run in a separate thread; boolean
  8062. :return:
  8063. """
  8064. self.report_usage("export_negative()")
  8065. if filename is None:
  8066. filename = self.defaults["global_last_save_folder"]
  8067. self.log.debug("export_svg() negative")
  8068. try:
  8069. obj = self.collection.get_by_name(str(obj_name))
  8070. except:
  8071. # TODO: The return behavior has not been established... should raise exception?
  8072. return "Could not retrieve object: %s" % obj_name
  8073. try:
  8074. box = self.collection.get_by_name(str(box_name))
  8075. except:
  8076. # TODO: The return behavior has not been established... should raise exception?
  8077. return "Could not retrieve object: %s" % box_name
  8078. if box is None:
  8079. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8080. (_("No object Box. Using instead"), obj))
  8081. box = obj
  8082. def make_negative_film():
  8083. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8084. # Determine bounding area for svg export
  8085. bounds = box.bounds()
  8086. size = box.size()
  8087. uom = obj.units.lower()
  8088. # Convert everything to strings for use in the xml doc
  8089. svgwidth = str(size[0] + (2 * boundary))
  8090. svgheight = str(size[1] + (2 * boundary))
  8091. minx = str(bounds[0] - boundary)
  8092. miny = str(bounds[1] + boundary + size[1])
  8093. miny_rect = str(bounds[1] - boundary)
  8094. # Add a SVG Header and footer to the svg output from shapely
  8095. # The transform flips the Y Axis so that everything renders
  8096. # properly within svg apps such as inkscape
  8097. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8098. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8099. svg_header += 'width="' + svgwidth + uom + '" '
  8100. svg_header += 'height="' + svgheight + uom + '" '
  8101. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8102. svg_header += '>'
  8103. svg_header += '<g transform="scale(1,-1)">'
  8104. svg_footer = '</g> </svg>'
  8105. # Change the attributes of the exported SVG
  8106. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8107. # We set opacity to maximum
  8108. # We set the color to WHITE
  8109. root = ET.fromstring(exported_svg)
  8110. for child in root:
  8111. child.set('fill', '#FFFFFF')
  8112. child.set('opacity', '1.0')
  8113. child.set('stroke', '#FFFFFF')
  8114. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8115. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8116. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8117. first_svg_elem_tag = 'rect'
  8118. first_svg_elem_attribs = {
  8119. 'x': minx,
  8120. 'y': miny_rect,
  8121. 'width': svgwidth,
  8122. 'height': svgheight,
  8123. 'id': 'neg_rect',
  8124. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8125. }
  8126. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8127. exported_svg = ET.tostring(root)
  8128. svg_elem = svg_header + str(exported_svg) + svg_footer
  8129. # Parse the xml through a xml parser just to add line feeds
  8130. # and to make it look more pretty for the output
  8131. doc = parse_xml_string(svg_elem)
  8132. try:
  8133. with open(filename, 'w') as fp:
  8134. fp.write(doc.toprettyxml())
  8135. except PermissionError:
  8136. self.inform.emit('[WARNING] %s' %
  8137. _("Permission denied, saving not possible.\n"
  8138. "Most likely another app is holding the file open and not accessible."))
  8139. return 'fail'
  8140. if self.defaults["global_open_style"] is False:
  8141. self.file_opened.emit("SVG", filename)
  8142. self.file_saved.emit("SVG", filename)
  8143. self.inform.emit('[success] %s: %s' %
  8144. (_("SVG file exported to"), filename))
  8145. if use_thread is True:
  8146. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8147. def job_thread_film(app_obj):
  8148. try:
  8149. make_negative_film()
  8150. except Exception as e:
  8151. proc.done()
  8152. return
  8153. proc.done()
  8154. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8155. else:
  8156. make_negative_film()
  8157. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8158. """
  8159. Exports a Geometry Object to an SVG file in positive black.
  8160. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8161. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8162. :param filename: Path to the SVG file to save to.
  8163. :param scale_factor: factor by which to change/scale the thickness of the features
  8164. :param use_thread: if to be run in a separate thread; boolean
  8165. :return:
  8166. """
  8167. self.report_usage("export_svg_positive()")
  8168. if filename is None:
  8169. filename = self.defaults["global_last_save_folder"]
  8170. self.log.debug("export_svg() black")
  8171. try:
  8172. obj = self.collection.get_by_name(str(obj_name))
  8173. except:
  8174. # TODO: The return behavior has not been established... should raise exception?
  8175. return "Could not retrieve object: %s" % obj_name
  8176. try:
  8177. box = self.collection.get_by_name(str(box_name))
  8178. except:
  8179. # TODO: The return behavior has not been established... should raise exception?
  8180. return "Could not retrieve object: %s" % box_name
  8181. if box is None:
  8182. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8183. (_("No object Box. Using instead"), obj))
  8184. box = obj
  8185. def make_positive_film():
  8186. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8187. self.progress.emit(40)
  8188. # Change the attributes of the exported SVG
  8189. # We don't need stroke-width
  8190. # We set opacity to maximum
  8191. # We set the colour to WHITE
  8192. root = ET.fromstring(exported_svg)
  8193. for child in root:
  8194. child.set('fill', str(self.defaults['tools_film_color']))
  8195. child.set('opacity', '1.0')
  8196. child.set('stroke', str(self.defaults['tools_film_color']))
  8197. exported_svg = ET.tostring(root)
  8198. # Determine bounding area for svg export
  8199. bounds = box.bounds()
  8200. size = box.size()
  8201. # This contain the measure units
  8202. uom = obj.units.lower()
  8203. # Define a boundary around SVG of about 1.0mm (~39mils)
  8204. if uom in "mm":
  8205. boundary = 1.0
  8206. else:
  8207. boundary = 0.0393701
  8208. self.progress.emit(80)
  8209. # Convert everything to strings for use in the xml doc
  8210. svgwidth = str(size[0] + (2 * boundary))
  8211. svgheight = str(size[1] + (2 * boundary))
  8212. minx = str(bounds[0] - boundary)
  8213. miny = str(bounds[1] + boundary + size[1])
  8214. self.log.debug(minx)
  8215. self.log.debug(miny)
  8216. # Add a SVG Header and footer to the svg output from shapely
  8217. # The transform flips the Y Axis so that everything renders
  8218. # properly within svg apps such as inkscape
  8219. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8220. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8221. svg_header += 'width="' + svgwidth + uom + '" '
  8222. svg_header += 'height="' + svgheight + uom + '" '
  8223. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8224. svg_header += '>'
  8225. svg_header += '<g transform="scale(1,-1)">'
  8226. svg_footer = '</g> </svg>'
  8227. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8228. self.progress.emit(90)
  8229. # Parse the xml through a xml parser just to add line feeds
  8230. # and to make it look more pretty for the output
  8231. doc = parse_xml_string(svg_elem)
  8232. try:
  8233. with open(filename, 'w') as fp:
  8234. fp.write(doc.toprettyxml())
  8235. except PermissionError:
  8236. self.inform.emit('[WARNING] %s' %
  8237. _("Permission denied, saving not possible.\n"
  8238. "Most likely another app is holding the file open and not accessible."))
  8239. return 'fail'
  8240. self.progress.emit(100)
  8241. if self.defaults["global_open_style"] is False:
  8242. self.file_opened.emit("SVG", filename)
  8243. self.file_saved.emit("SVG", filename)
  8244. self.inform.emit('[success] %s: %s' %
  8245. (_("SVG file exported to"), filename))
  8246. if use_thread is True:
  8247. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8248. def job_thread_film(app_obj):
  8249. try:
  8250. make_positive_film()
  8251. except Exception as e:
  8252. proc.done()
  8253. return
  8254. proc.done()
  8255. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8256. else:
  8257. make_positive_film()
  8258. def save_source_file(self, obj_name, filename, use_thread=True):
  8259. """
  8260. Exports a FlatCAM Object to an Gerber/Excellon file.
  8261. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8262. :param filename: Path to the Gerber file to save to.
  8263. :param use_thread: if to be run in a separate thread
  8264. :return:
  8265. """
  8266. self.report_usage("save source file()")
  8267. if filename is None:
  8268. filename = self.defaults["global_last_save_folder"]
  8269. self.log.debug("save source file()")
  8270. obj = self.collection.get_by_name(obj_name)
  8271. file_string = StringIO(obj.source_file)
  8272. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8273. try:
  8274. with open(filename, 'w') as file:
  8275. file.writelines('G04*\n')
  8276. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8277. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8278. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8279. file.writelines('G04 Created on : %s*\n' % time_string)
  8280. for line in file_string:
  8281. file.writelines(line)
  8282. except PermissionError:
  8283. self.inform.emit('[WARNING] %s' %
  8284. _("Permission denied, saving not possible.\n"
  8285. "Most likely another app is holding the file open and not accessible."))
  8286. return 'fail'
  8287. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8288. """
  8289. Exports a Excellon Object to an Excellon file.
  8290. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8291. :param filename: Path to the Excellon file to save to.
  8292. :param use_thread: if to be run in a separate thread
  8293. :return:
  8294. """
  8295. self.report_usage("export_excellon()")
  8296. if filename is None:
  8297. filename = self.defaults["global_last_save_folder"]
  8298. self.log.debug("export_excellon()")
  8299. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8300. self.defaults["excellon_exp_decimals"]
  8301. )
  8302. if local_use is None:
  8303. try:
  8304. obj = self.collection.get_by_name(str(obj_name))
  8305. except:
  8306. # TODO: The return behavior has not been established... should raise exception?
  8307. return "Could not retrieve object: %s" % obj_name
  8308. else:
  8309. obj = local_use
  8310. # updated units
  8311. eunits = self.defaults["excellon_exp_units"]
  8312. ewhole = self.defaults["excellon_exp_integer"]
  8313. efract = self.defaults["excellon_exp_decimals"]
  8314. ezeros = self.defaults["excellon_exp_zeros"]
  8315. eformat = self.defaults["excellon_exp_format"]
  8316. slot_type = self.defaults["excellon_exp_slot_type"]
  8317. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8318. if fc_units == 'MM':
  8319. factor = 1 if eunits == 'METRIC' else 0.03937
  8320. else:
  8321. factor = 25.4 if eunits == 'METRIC' else 1
  8322. def make_excellon():
  8323. try:
  8324. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8325. header = 'M48\n'
  8326. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8327. (str(self.version), str(self.version_date))
  8328. header += ';Filename: %s' % str(obj_name) + '\n'
  8329. header += ';Created on : %s' % time_str + '\n'
  8330. if eformat == 'dec':
  8331. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8332. header += eunits + '\n'
  8333. for tool in obj.tools:
  8334. if eunits == 'METRIC':
  8335. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8336. tool=str(tool),
  8337. dec=2)
  8338. else:
  8339. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8340. tool=str(tool),
  8341. dec=4)
  8342. else:
  8343. if ezeros == 'LZ':
  8344. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8345. form='ndec', e_zeros='LZ', factor=factor,
  8346. slot_type=slot_type)
  8347. header += '%s,%s\n' % (eunits, 'LZ')
  8348. header += format_exc
  8349. for tool in obj.tools:
  8350. if eunits == 'METRIC':
  8351. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8352. tool=str(tool),
  8353. dec=2)
  8354. else:
  8355. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8356. tool=str(tool),
  8357. dec=4)
  8358. else:
  8359. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8360. form='ndec', e_zeros='TZ', factor=factor,
  8361. slot_type=slot_type)
  8362. header += '%s,%s\n' % (eunits, 'TZ')
  8363. header += format_exc
  8364. for tool in obj.tools:
  8365. if eunits == 'METRIC':
  8366. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8367. tool=str(tool),
  8368. dec=2)
  8369. else:
  8370. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8371. tool=str(tool),
  8372. dec=4)
  8373. header += '%\n'
  8374. footer = 'M30\n'
  8375. exported_excellon = header
  8376. exported_excellon += excellon_code
  8377. exported_excellon += footer
  8378. if local_use is None:
  8379. try:
  8380. with open(filename, 'w') as fp:
  8381. fp.write(exported_excellon)
  8382. except PermissionError:
  8383. self.inform.emit('[WARNING] %s' %
  8384. _("Permission denied, saving not possible.\n"
  8385. "Most likely another app is holding the file open and not accessible."))
  8386. return 'fail'
  8387. if self.defaults["global_open_style"] is False:
  8388. self.file_opened.emit("Excellon", filename)
  8389. self.file_saved.emit("Excellon", filename)
  8390. self.inform.emit('[success] %s: %s' %
  8391. (_("Excellon file exported to"), filename))
  8392. else:
  8393. return exported_excellon
  8394. except Exception as e:
  8395. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8396. return 'fail'
  8397. if use_thread is True:
  8398. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8399. def job_thread_exc(app_obj):
  8400. ret = make_excellon()
  8401. if ret == 'fail':
  8402. self.inform.emit('[ERROR_NOTCL] %s' %
  8403. _('Could not export Excellon file.'))
  8404. return
  8405. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8406. else:
  8407. ret = make_excellon()
  8408. if ret == 'fail':
  8409. self.inform.emit('[ERROR_NOTCL] %s' %
  8410. _('Could not export Excellon file.'))
  8411. return 'fail'
  8412. if local_use is not None:
  8413. return ret
  8414. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8415. """
  8416. Exports a Gerber Object to an Gerber file.
  8417. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8418. :param filename: Path to the Gerber file to save to.
  8419. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8420. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8421. :param use_thread: if to be run in a separate thread
  8422. :return:
  8423. """
  8424. self.report_usage("export_gerber()")
  8425. if filename is None:
  8426. filename = self.defaults["global_last_save_folder"]
  8427. self.log.debug("export_gerber()")
  8428. if local_use is None:
  8429. try:
  8430. obj = self.collection.get_by_name(str(obj_name))
  8431. except:
  8432. # TODO: The return behavior has not been established... should raise exception?
  8433. return "Could not retrieve object: %s" % obj_name
  8434. else:
  8435. obj = local_use
  8436. # updated units
  8437. gunits = self.defaults["gerber_exp_units"]
  8438. gwhole = self.defaults["gerber_exp_integer"]
  8439. gfract = self.defaults["gerber_exp_decimals"]
  8440. gzeros = self.defaults["gerber_exp_zeros"]
  8441. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8442. if fc_units == 'MM':
  8443. factor = 1 if gunits == 'MM' else 0.03937
  8444. else:
  8445. factor = 25.4 if gunits == 'MM' else 1
  8446. def make_gerber():
  8447. try:
  8448. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8449. header = 'G04*\n'
  8450. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8451. (str(self.version), str(self.version_date))
  8452. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8453. header += 'G04 Created on : %s*' % time_str + '\n'
  8454. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8455. header += "%MO{units}*%\n".format(units=gunits)
  8456. for apid in obj.apertures:
  8457. if obj.apertures[apid]['type'] == 'C':
  8458. header += "%ADD{apid}{type},{size}*%\n".format(
  8459. apid=str(apid),
  8460. type='C',
  8461. size=(factor * obj.apertures[apid]['size'])
  8462. )
  8463. elif obj.apertures[apid]['type'] == 'R':
  8464. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8465. apid=str(apid),
  8466. type='R',
  8467. width=(factor * obj.apertures[apid]['width']),
  8468. height=(factor * obj.apertures[apid]['height'])
  8469. )
  8470. elif obj.apertures[apid]['type'] == 'O':
  8471. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8472. apid=str(apid),
  8473. type='O',
  8474. width=(factor * obj.apertures[apid]['width']),
  8475. height=(factor * obj.apertures[apid]['height'])
  8476. )
  8477. header += '\n'
  8478. # obsolete units but some software may need it
  8479. if gunits == 'IN':
  8480. header += 'G70*\n'
  8481. else:
  8482. header += 'G71*\n'
  8483. # Absolute Mode
  8484. header += 'G90*\n'
  8485. header += 'G01*\n'
  8486. # positive polarity
  8487. header += '%LPD*%\n'
  8488. footer = 'M02*\n'
  8489. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8490. exported_gerber = header
  8491. exported_gerber += gerber_code
  8492. exported_gerber += footer
  8493. if local_use is None:
  8494. try:
  8495. with open(filename, 'w') as fp:
  8496. fp.write(exported_gerber)
  8497. except PermissionError:
  8498. self.inform.emit('[WARNING] %s' %
  8499. _("Permission denied, saving not possible.\n"
  8500. "Most likely another app is holding the file open and not accessible."))
  8501. return 'fail'
  8502. if self.defaults["global_open_style"] is False:
  8503. self.file_opened.emit("Gerber", filename)
  8504. self.file_saved.emit("Gerber", filename)
  8505. self.inform.emit('[success] %s: %s' %
  8506. (_("Gerber file exported to"), filename))
  8507. else:
  8508. return exported_gerber
  8509. except Exception as e:
  8510. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8511. return 'fail'
  8512. if use_thread is True:
  8513. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8514. def job_thread_grb(app_obj):
  8515. ret = make_gerber()
  8516. if ret == 'fail':
  8517. self.inform.emit('[ERROR_NOTCL] %s' %
  8518. _('Could not export Gerber file.'))
  8519. return
  8520. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8521. else:
  8522. ret = make_gerber()
  8523. if ret == 'fail':
  8524. self.inform.emit('[ERROR_NOTCL] %s' %
  8525. _('Could not export Gerber file.'))
  8526. return 'fail'
  8527. if local_use is not None:
  8528. return ret
  8529. def export_dxf(self, obj_name, filename, use_thread=True):
  8530. """
  8531. Exports a Geometry Object to an DXF file.
  8532. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8533. :param filename: Path to the DXF file to save to.
  8534. :param use_thread: if to be run in a separate thread
  8535. :return:
  8536. """
  8537. self.report_usage("export_dxf()")
  8538. if filename is None:
  8539. filename = self.defaults["global_last_save_folder"]
  8540. self.log.debug("export_dxf()")
  8541. format_exc = ''
  8542. units = ''
  8543. try:
  8544. obj = self.collection.get_by_name(str(obj_name))
  8545. except:
  8546. # TODO: The return behavior has not been established... should raise exception?
  8547. return "Could not retrieve object: %s" % obj_name
  8548. # updated units
  8549. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8550. if units == 'IN' or units == 'INCH':
  8551. units = 'INCH'
  8552. elif units == 'MM' or units == 'METIRC':
  8553. units ='METRIC'
  8554. def make_dxf():
  8555. try:
  8556. dxf_code = obj.export_dxf()
  8557. dxf_code.saveas(filename)
  8558. if self.defaults["global_open_style"] is False:
  8559. self.file_opened.emit("DXF", filename)
  8560. self.file_saved.emit("DXF", filename)
  8561. self.inform.emit('[success] %s: %s' %
  8562. (_("DXF file exported to"), filename))
  8563. except:
  8564. return 'fail'
  8565. if use_thread is True:
  8566. with self.proc_container.new(_("Exporting DXF")) as proc:
  8567. def job_thread_exc(app_obj):
  8568. ret = make_dxf()
  8569. if ret == 'fail':
  8570. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8571. _('Could not export DXF file.'))
  8572. return
  8573. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8574. else:
  8575. ret = make_dxf()
  8576. if ret == 'fail':
  8577. self.inform.emit('[WARNING_NOTCL] %s' %
  8578. _('Could not export DXF file.'))
  8579. return
  8580. def import_svg(self, filename, geo_type='geometry', outname=None):
  8581. """
  8582. Adds a new Geometry Object to the projects and populates
  8583. it with shapes extracted from the SVG file.
  8584. :param filename: Path to the SVG file.
  8585. :param geo_type: Type of FlatCAM object that will be created from SVG
  8586. :param outname:
  8587. :return:
  8588. """
  8589. self.report_usage("import_svg()")
  8590. obj_type = ""
  8591. if geo_type is None or geo_type == "geometry":
  8592. obj_type = "geometry"
  8593. elif geo_type == "gerber":
  8594. obj_type = geo_type
  8595. else:
  8596. self.inform.emit('[ERROR_NOTCL] %s' %
  8597. _("Not supported type is picked as parameter. "
  8598. "Only Geometry and Gerber are supported"))
  8599. return
  8600. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8601. def obj_init(geo_obj, app_obj):
  8602. geo_obj.import_svg(filename, obj_type, units=units)
  8603. geo_obj.multigeo = False
  8604. with self.proc_container.new(_("Importing SVG")) as proc:
  8605. # Object name
  8606. name = outname or filename.split('/')[-1].split('\\')[-1]
  8607. self.new_object(obj_type, name, obj_init, autoselected=False)
  8608. self.progress.emit(20)
  8609. # Register recent file
  8610. self.file_opened.emit("svg", filename)
  8611. # GUI feedback
  8612. self.inform.emit('[success] %s: %s' %
  8613. (_("Opened"), filename))
  8614. self.progress.emit(100)
  8615. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8616. """
  8617. Adds a new Geometry Object to the projects and populates
  8618. it with shapes extracted from the DXF file.
  8619. :param filename: Path to the DXF file.
  8620. :param geo_type: Type of FlatCAM object that will be created from DXF
  8621. :param outname:
  8622. :type putname: str
  8623. :return:
  8624. """
  8625. self.report_usage("import_dxf()")
  8626. obj_type = ""
  8627. if geo_type is None or geo_type == "geometry":
  8628. obj_type = "geometry"
  8629. elif geo_type == "gerber":
  8630. obj_type = geo_type
  8631. else:
  8632. self.inform.emit('[ERROR_NOTCL] %s' %
  8633. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8634. return
  8635. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8636. def obj_init(geo_obj, app_obj):
  8637. geo_obj.import_dxf(filename, obj_type, units=units)
  8638. geo_obj.multigeo = False
  8639. with self.proc_container.new(_("Importing DXF")) as proc:
  8640. # Object name
  8641. name = outname or filename.split('/')[-1].split('\\')[-1]
  8642. self.new_object(obj_type, name, obj_init, autoselected=False)
  8643. self.progress.emit(20)
  8644. # Register recent file
  8645. self.file_opened.emit("dxf", filename)
  8646. # GUI feedback
  8647. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8648. self.progress.emit(100)
  8649. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8650. """
  8651. Adds a new Geometry Object to the projects and populates
  8652. it with shapes extracted from the SVG file.
  8653. :param filename: Path to the SVG file.
  8654. :param o_type: type of FlatCAM objeect
  8655. :param dpi: dot per inch
  8656. :param mode: black or color
  8657. :param mask: dictate the level of detail
  8658. :param outname: name for the resulting file
  8659. :return:
  8660. """
  8661. self.report_usage("import_image()")
  8662. if o_type is None or o_type == "geometry":
  8663. obj_type = "geometry"
  8664. elif o_type == "gerber":
  8665. obj_type = o_type
  8666. else:
  8667. self.inform.emit('[ERROR_NOTCL] %s' %
  8668. _("Not supported type is picked as parameter. "
  8669. "Only Geometry and Gerber are supported"))
  8670. return
  8671. def obj_init(geo_obj, app_obj):
  8672. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8673. geo_obj.multigeo = False
  8674. with self.proc_container.new(_("Importing Image")) as proc:
  8675. # Object name
  8676. name = outname or filename.split('/')[-1].split('\\')[-1]
  8677. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8678. self.new_object(obj_type, name, obj_init)
  8679. self.progress.emit(20)
  8680. # Register recent file
  8681. self.file_opened.emit("image", filename)
  8682. # GUI feedback
  8683. self.inform.emit('[success] %s: %s' %
  8684. (_("Opened"), filename))
  8685. self.progress.emit(100)
  8686. def open_gerber(self, filename, outname=None):
  8687. """
  8688. Opens a Gerber file, parses it and creates a new object for
  8689. it in the program. Thread-safe.
  8690. :param outname: Name of the resulting object. None causes the
  8691. name to be that of the file.
  8692. :param filename: Gerber file filename
  8693. :type filename: str
  8694. :param follow: If true, the parser will not create polygons, just lines
  8695. following the gerber path.
  8696. :type follow: bool
  8697. :return: None
  8698. """
  8699. # How the object should be initialized
  8700. def obj_init(gerber_obj, app_obj):
  8701. assert isinstance(gerber_obj, FlatCAMGerber), \
  8702. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8703. # Opening the file happens here
  8704. self.progress.emit(30)
  8705. try:
  8706. gerber_obj.parse_file(filename)
  8707. except IOError:
  8708. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8709. (_("Failed to open file"), filename))
  8710. app_obj.progress.emit(0)
  8711. return "fail"
  8712. except ParseError as err:
  8713. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8714. (_("Failed to parse file"), filename, str(err)))
  8715. app_obj.progress.emit(0)
  8716. self.log.error(str(err))
  8717. return "fail"
  8718. except Exception as e:
  8719. log.debug("App.open_gerber() --> %s" % str(e))
  8720. msg = '[ERROR] %s' % \
  8721. _("An internal error has occurred. See shell.\n")
  8722. msg += traceback.format_exc()
  8723. app_obj.inform.emit(msg)
  8724. return "fail"
  8725. if gerber_obj.is_empty():
  8726. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8727. # self.collection.set_active(gerber_obj.options["name"])
  8728. # self.collection.delete_active()
  8729. self.inform.emit('[ERROR_NOTCL] %s' %
  8730. _("Object is not Gerber file or empty. Aborting object creation."))
  8731. return "fail"
  8732. # Further parsing
  8733. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8734. App.log.debug("open_gerber()")
  8735. with self.proc_container.new(_("Opening Gerber")) as proc:
  8736. self.progress.emit(10)
  8737. # Object name
  8738. name = outname or filename.split('/')[-1].split('\\')[-1]
  8739. # # ## Object creation # ##
  8740. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8741. if ret == 'fail':
  8742. self.inform.emit('[ERROR_NOTCL]%s' %
  8743. _(' Open Gerber failed. Probable not a Gerber file.'))
  8744. return
  8745. # Register recent file
  8746. self.file_opened.emit("gerber", filename)
  8747. self.progress.emit(100)
  8748. # GUI feedback
  8749. self.inform.emit('[success] %s: %s' %
  8750. (_("Opened"), filename))
  8751. def open_excellon(self, filename, outname=None, plot=True):
  8752. """
  8753. Opens an Excellon file, parses it and creates a new object for
  8754. it in the program. Thread-safe.
  8755. :param outname: Name of the resulting object. None causes the
  8756. name to be that of the file.
  8757. :param filename: Excellon file filename
  8758. :type filename: str
  8759. :return: None
  8760. """
  8761. App.log.debug("open_excellon()")
  8762. # How the object should be initialized
  8763. def obj_init(excellon_obj, app_obj):
  8764. # self.progress.emit(20)
  8765. try:
  8766. ret = excellon_obj.parse_file(filename=filename)
  8767. if ret == "fail":
  8768. log.debug("Excellon parsing failed.")
  8769. self.inform.emit('[ERROR_NOTCL] %s' %
  8770. _("This is not Excellon file."))
  8771. return "fail"
  8772. except IOError:
  8773. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8774. (_("Cannot open file"), filename))
  8775. log.debug("Could not open Excellon object.")
  8776. self.progress.emit(0) # TODO: self and app_bjj mixed
  8777. return "fail"
  8778. except:
  8779. msg = '[ERROR_NOTCL] %s' % \
  8780. _("An internal error has occurred. See shell.\n")
  8781. msg += traceback.format_exc()
  8782. app_obj.inform.emit(msg)
  8783. return "fail"
  8784. ret = excellon_obj.create_geometry()
  8785. if ret == 'fail':
  8786. log.debug("Could not create geometry for Excellon object.")
  8787. return "fail"
  8788. for tool in excellon_obj.tools:
  8789. if excellon_obj.tools[tool]['solid_geometry']:
  8790. return
  8791. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8792. (_("No geometry found in file"), filename))
  8793. return "fail"
  8794. with self.proc_container.new(_("Opening Excellon.")):
  8795. # Object name
  8796. name = outname or filename.split('/')[-1].split('\\')[-1]
  8797. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8798. if ret_val == 'fail':
  8799. self.inform.emit('[ERROR_NOTCL] %s' %
  8800. _('Open Excellon file failed. Probable not an Excellon file.'))
  8801. return
  8802. # Register recent file
  8803. self.file_opened.emit("excellon", filename)
  8804. # GUI feedback
  8805. self.inform.emit('[success] %s: %s' %
  8806. (_("Opened"), filename))
  8807. def open_gcode(self, filename, outname=None, plot=True):
  8808. """
  8809. Opens a G-gcode file, parses it and creates a new object for
  8810. it in the program. Thread-safe.
  8811. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8812. :param filename: G-code file filename
  8813. :type filename: str
  8814. :return: None
  8815. """
  8816. App.log.debug("open_gcode()")
  8817. # How the object should be initialized
  8818. def obj_init(job_obj, app_obj_):
  8819. """
  8820. :param job_obj: the resulting object
  8821. :type app_obj_: App
  8822. """
  8823. assert isinstance(app_obj_, App), \
  8824. "Initializer expected App, got %s" % type(app_obj_)
  8825. try:
  8826. f = open(filename)
  8827. gcode = f.read()
  8828. f.close()
  8829. except IOError:
  8830. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8831. (_("Failed to open"), filename))
  8832. return "fail"
  8833. job_obj.gcode = gcode
  8834. ret = job_obj.gcode_parse()
  8835. if ret == "fail":
  8836. self.inform.emit('[ERROR_NOTCL] %s' %
  8837. _("This is not GCODE"))
  8838. return "fail"
  8839. job_obj.create_geometry()
  8840. with self.proc_container.new(_("Opening G-Code.")):
  8841. # Object name
  8842. name = outname or filename.split('/')[-1].split('\\')[-1]
  8843. # New object creation and file processing
  8844. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8845. if ret == 'fail':
  8846. self.inform.emit('[ERROR_NOTCL] %s' %
  8847. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8848. "Attempting to create a FlatCAM CNCJob Object from "
  8849. "G-Code file failed during processing"))
  8850. return "fail"
  8851. # Register recent file
  8852. self.file_opened.emit("cncjob", filename)
  8853. # GUI feedback
  8854. self.inform.emit('[success] %s: %s' %
  8855. (_("Opened"), filename))
  8856. def open_script(self, filename, outname=None, silent=False):
  8857. """
  8858. Opens a Script file, parses it and creates a new object for
  8859. it in the program. Thread-safe.
  8860. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8861. :param filename: Script file filename
  8862. :type filename: str
  8863. :return: None
  8864. """
  8865. App.log.debug("open_script()")
  8866. with self.proc_container.new(_("Opening TCL Script...")):
  8867. try:
  8868. with open(filename, "r") as opened_script:
  8869. script_content = opened_script.readlines()
  8870. script_content = ''.join(script_content)
  8871. if silent is False:
  8872. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8873. except Exception as e:
  8874. log.debug("App.open_script() -> %s" % str(e))
  8875. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8876. return
  8877. # Object name
  8878. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8879. # New object creation and file processing
  8880. self.on_filenewscript(name=script_name, text=script_content)
  8881. # Register recent file
  8882. self.file_opened.emit("script", filename)
  8883. # GUI feedback
  8884. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8885. def open_config_file(self, filename, run_from_arg=None):
  8886. """
  8887. Loads a config file from the specified file.
  8888. :param filename: Name of the file from which to load.
  8889. :type filename: str
  8890. :return: None
  8891. """
  8892. App.log.debug("Opening config file: " + filename)
  8893. if run_from_arg:
  8894. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8895. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8896. _("Opening FlatCAM Config file.")),
  8897. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8898. color=QtGui.QColor("gray"))
  8899. # add the tab if it was closed
  8900. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8901. # first clear previous text in text editor (if any)
  8902. self.ui.text_editor_tab.code_editor.clear()
  8903. # Switch plot_area to CNCJob tab
  8904. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8905. try:
  8906. if filename:
  8907. f = QtCore.QFile(filename)
  8908. if f.open(QtCore.QIODevice.ReadOnly):
  8909. stream = QtCore.QTextStream(f)
  8910. gcode_edited = stream.readAll()
  8911. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  8912. f.close()
  8913. except IOError:
  8914. App.log.error("Failed to open config file: %s" % filename)
  8915. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8916. (_("Failed to open config file"), filename))
  8917. return
  8918. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8919. """
  8920. Loads a project from the specified file.
  8921. 1) Loads and parses file
  8922. 2) Registers the file as recently opened.
  8923. 3) Calls on_file_new()
  8924. 4) Updates options
  8925. 5) Calls new_object() with the object's from_dict() as init method.
  8926. 6) Calls plot_all() if plot=True
  8927. :param filename: Name of the file from which to load.
  8928. :type filename: str
  8929. :param run_from_arg: True if run for arguments
  8930. :param plot: If True plot all objects in the project
  8931. :param cli: run from command line
  8932. :return: None
  8933. """
  8934. App.log.debug("Opening project: " + filename)
  8935. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8936. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8937. if cli is None:
  8938. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8939. if run_from_arg:
  8940. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8941. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8942. _("Opening FlatCAM Project file.")),
  8943. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8944. color=QtGui.QColor("gray"))
  8945. # Open and parse an uncompressed Project file
  8946. try:
  8947. f = open(filename, 'r')
  8948. except IOError:
  8949. App.log.error("Failed to open project file: %s" % filename)
  8950. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8951. (_("Failed to open project file"), filename))
  8952. return
  8953. try:
  8954. d = json.load(f, object_hook=dict2obj)
  8955. except Exception as e:
  8956. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8957. (filename, str(e)))
  8958. f.close()
  8959. # Open and parse a compressed Project file
  8960. try:
  8961. with lzma.open(filename) as f:
  8962. file_content = f.read().decode('utf-8')
  8963. d = json.loads(file_content, object_hook=dict2obj)
  8964. except Exception as e:
  8965. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8966. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8967. (_("Failed to open project file"), filename))
  8968. return
  8969. # Clear the current project
  8970. # # NOT THREAD SAFE # ##
  8971. if run_from_arg is True:
  8972. pass
  8973. elif cli is True:
  8974. self.delete_selection_shape()
  8975. else:
  8976. self.on_file_new()
  8977. # Project options
  8978. self.options.update(d['options'])
  8979. self.project_filename = filename
  8980. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8981. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8982. if cli is None:
  8983. self.set_screen_units(self.options["units"])
  8984. # Re create objects
  8985. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8986. for obj in d['objs']:
  8987. def obj_init(obj_inst, app_inst):
  8988. obj_inst.from_dict(obj)
  8989. App.log.debug("Recreating from opened project an %s object: %s" %
  8990. (obj['kind'].capitalize(), obj['options']['name']))
  8991. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8992. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8993. if cli is None:
  8994. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8995. obj['kind'].upper(),
  8996. obj['options']['name']
  8997. )
  8998. )
  8999. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9000. self.inform.emit('[success] %s: %s' %
  9001. (_("Project loaded from"), filename))
  9002. self.should_we_save = False
  9003. self.file_opened.emit("project", filename)
  9004. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9005. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9006. if cli is None:
  9007. self.set_ui_title(name=self.project_filename)
  9008. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9009. def propagate_defaults(self, silent=False):
  9010. """
  9011. This method is used to set default values in classes. It's
  9012. an alternative to project options but allows the use
  9013. of values invisible to the user.
  9014. :return: None
  9015. """
  9016. if silent is False:
  9017. self.log.debug("propagate_defaults()")
  9018. # Which objects to update the given parameters.
  9019. routes = {
  9020. "global_zdownrate": CNCjob,
  9021. "excellon_zeros": Excellon,
  9022. "excellon_format_upper_in": Excellon,
  9023. "excellon_format_lower_in": Excellon,
  9024. "excellon_format_upper_mm": Excellon,
  9025. "excellon_format_lower_mm": Excellon,
  9026. "excellon_units": Excellon,
  9027. "gerber_use_buffer_for_union": Gerber,
  9028. "geometry_multidepth": Geometry
  9029. }
  9030. for param in routes:
  9031. if param in routes[param].defaults:
  9032. try:
  9033. routes[param].defaults[param] = self.defaults[param]
  9034. if silent is False:
  9035. self.log.debug(" " + param + " OK")
  9036. except KeyError:
  9037. if silent is False:
  9038. self.log.debug(" ERROR: " + param + " not in defaults.")
  9039. else:
  9040. # Try extracting the name:
  9041. # classname_param here is param in the object
  9042. if param.find(routes[param].__name__.lower() + "_") == 0:
  9043. p = param[len(routes[param].__name__) + 1:]
  9044. if p in routes[param].defaults:
  9045. routes[param].defaults[p] = self.defaults[param]
  9046. if silent is False:
  9047. self.log.debug(" " + param + " OK!")
  9048. def plot_all(self, zoom=True):
  9049. """
  9050. Re-generates all plots from all objects.
  9051. :return: None
  9052. """
  9053. self.log.debug("Plot_all()")
  9054. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9055. for obj in self.collection.get_list():
  9056. def worker_task(obj):
  9057. with self.proc_container.new("Plotting"):
  9058. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9059. if zoom:
  9060. self.object_plotted.emit(obj)
  9061. # Send to worker
  9062. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9063. def register_folder(self, filename):
  9064. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9065. def register_save_folder(self, filename):
  9066. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9067. def set_progress_bar(self, percentage, text=""):
  9068. self.ui.progress_bar.setValue(int(percentage))
  9069. def setup_shell(self):
  9070. """
  9071. Creates shell functions. Runs once at startup.
  9072. :return: None
  9073. """
  9074. self.log.debug("setup_shell()")
  9075. def shelp(p=None):
  9076. if not p:
  9077. return _("Available commands:\n") + \
  9078. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9079. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9080. if p not in commands:
  9081. return "Unknown command: %s" % p
  9082. return commands[p]["help"]
  9083. # --- Migrated to new architecture ---
  9084. # def options(name):
  9085. # ops = self.collection.get_by_name(str(name)).options
  9086. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9087. def h(*args):
  9088. """
  9089. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9090. and standalone parameters into list.
  9091. """
  9092. kwa = {}
  9093. a = []
  9094. n = len(args)
  9095. name = None
  9096. for i in range(n):
  9097. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9098. if match:
  9099. assert name is None
  9100. name = match.group(1)
  9101. continue
  9102. if name is None:
  9103. a.append(args[i])
  9104. else:
  9105. kwa[name] = args[i]
  9106. name = None
  9107. return a, kwa
  9108. @contextmanager
  9109. def wait_signal(signal, timeout=10000):
  9110. """
  9111. Block loop until signal emitted, timeout (ms) elapses
  9112. or unhandled exception happens in a thread.
  9113. :param timeout: time after which the loop is exited
  9114. :param signal: Signal to wait for.
  9115. """
  9116. loop = QtCore.QEventLoop()
  9117. # Normal termination
  9118. signal.connect(loop.quit)
  9119. # Termination by exception in thread
  9120. self.thread_exception.connect(loop.quit)
  9121. status = {'timed_out': False}
  9122. def report_quit():
  9123. status['timed_out'] = True
  9124. loop.quit()
  9125. yield
  9126. # Temporarily change how exceptions are managed.
  9127. oeh = sys.excepthook
  9128. ex = []
  9129. def except_hook(type_, value, traceback_):
  9130. ex.append(value)
  9131. oeh(type_, value, traceback_)
  9132. sys.excepthook = except_hook
  9133. # Terminate on timeout
  9134. if timeout is not None:
  9135. QtCore.QTimer.singleShot(timeout, report_quit)
  9136. # # ## Block ## ##
  9137. loop.exec_()
  9138. # Restore exception management
  9139. sys.excepthook = oeh
  9140. if ex:
  9141. self.raiseTclError(str(ex[0]))
  9142. if status['timed_out']:
  9143. raise Exception('Timed out!')
  9144. def make_docs():
  9145. output = ''
  9146. import collections
  9147. od = collections.OrderedDict(sorted(commands.items()))
  9148. for cmd_, val in od.items():
  9149. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9150. t = val['help']
  9151. usage_i = t.find('>')
  9152. if usage_i < 0:
  9153. expl = t
  9154. output += expl + '\n\n'
  9155. continue
  9156. expl = t[:usage_i - 1]
  9157. output += expl + '\n\n'
  9158. end_usage_i = t[usage_i:].find('\n')
  9159. if end_usage_i < 0:
  9160. end_usage_i = len(t[usage_i:])
  9161. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9162. else:
  9163. extras = t[usage_i+end_usage_i+1:]
  9164. parts = [s.strip() for s in extras.split('\n')]
  9165. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9166. for p in parts:
  9167. output += ' ' + p + '\n\n'
  9168. return output
  9169. '''
  9170. Howto implement TCL shell commands:
  9171. All parameters passed to command should be possible to set as None and test it afterwards.
  9172. This is because we need to see error caused in tcl,
  9173. if None value as default parameter is not allowed TCL will return empty error.
  9174. Use:
  9175. def mycommand(name=None,...):
  9176. Test it like this:
  9177. if name is None:
  9178. self.raise_tcl_error('Argument name is missing.')
  9179. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9180. otherwise we will miss it and processing will silently continue.
  9181. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9182. which is catched in exec_command and displayed in TCL shell console with red background.
  9183. Error in console is displayed with TCL trace.
  9184. This behavior works only within main thread,
  9185. errors with promissed tasks can be catched and detected only with log.
  9186. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9187. TCL shell.
  9188. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9189. '''
  9190. commands = {
  9191. 'help': {
  9192. 'fcn': shelp,
  9193. 'help': _("Shows list of commands.")
  9194. },
  9195. }
  9196. # Import/overwrite tcl commands as objects of TclCommand descendants
  9197. # This modifies the variable 'commands'.
  9198. tclCommands.register_all_commands(self, commands)
  9199. # Add commands to the tcl interpreter
  9200. for cmd in commands:
  9201. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9202. # Make the tcl puts function return instead of print to stdout
  9203. self.tcl.eval('''
  9204. rename puts original_puts
  9205. proc puts {args} {
  9206. if {[llength $args] == 1} {
  9207. return "[lindex $args 0]"
  9208. } else {
  9209. eval original_puts $args
  9210. }
  9211. }
  9212. ''')
  9213. def setup_recent_items(self):
  9214. # TODO: Move this to constructor
  9215. icons = {
  9216. "gerber": "share/flatcam_icon16.png",
  9217. "excellon": "share/drill16.png",
  9218. 'geometry': "share/geometry16.png",
  9219. "cncjob": "share/cnc16.png",
  9220. "script": "share/script_new24.png",
  9221. "document": "share/notes16_1.png",
  9222. "project": "share/project16.png",
  9223. "svg": "share/geometry16.png",
  9224. "dxf": "share/dxf16.png",
  9225. "pdf": "share/pdf32.png",
  9226. "image": "share/image16.png"
  9227. }
  9228. openers = {
  9229. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9230. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9231. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9232. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9233. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9234. "document": None,
  9235. 'project': self.open_project,
  9236. 'svg': self.import_svg,
  9237. 'dxf': self.import_dxf,
  9238. 'image': self.import_image,
  9239. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9240. }
  9241. # Open recent file for files
  9242. try:
  9243. f = open(self.data_path + '/recent.json')
  9244. except IOError:
  9245. App.log.error("Failed to load recent item list.")
  9246. self.inform.emit('[ERROR_NOTCL] %s' %
  9247. _("Failed to load recent item list."))
  9248. return
  9249. try:
  9250. self.recent = json.load(f)
  9251. except json.scanner.JSONDecodeError:
  9252. App.log.error("Failed to parse recent item list.")
  9253. self.inform.emit('[ERROR_NOTCL] %s' %
  9254. _("Failed to parse recent item list."))
  9255. f.close()
  9256. return
  9257. f.close()
  9258. # Open recent file for projects
  9259. try:
  9260. fp = open(self.data_path + '/recent_projects.json')
  9261. except IOError:
  9262. App.log.error("Failed to load recent project item list.")
  9263. self.inform.emit('[ERROR_NOTCL] %s' %
  9264. _("Failed to load recent projects item list."))
  9265. return
  9266. try:
  9267. self.recent_projects = json.load(fp)
  9268. except json.scanner.JSONDecodeError:
  9269. App.log.error("Failed to parse recent project item list.")
  9270. self.inform.emit('[ERROR_NOTCL] %s' %
  9271. _("Failed to parse recent project item list."))
  9272. fp.close()
  9273. return
  9274. fp.close()
  9275. # Closure needed to create callbacks in a loop.
  9276. # Otherwise late binding occurs.
  9277. def make_callback(func, fname):
  9278. def opener():
  9279. func(fname)
  9280. return opener
  9281. def reset_recent_files():
  9282. # Reset menu
  9283. self.ui.recent.clear()
  9284. self.recent = []
  9285. try:
  9286. f = open(self.data_path + '/recent.json', 'w')
  9287. except IOError:
  9288. App.log.error("Failed to open recent items file for writing.")
  9289. return
  9290. json.dump(self.recent, f)
  9291. def reset_recent_projects():
  9292. # Reset menu
  9293. self.ui.recent_projects.clear()
  9294. self.recent_projects = []
  9295. try:
  9296. fp = open(self.data_path + '/recent_projects.json', 'w')
  9297. except IOError:
  9298. App.log.error("Failed to open recent projects items file for writing.")
  9299. return
  9300. json.dump(self.recent, fp)
  9301. # Reset menu
  9302. self.ui.recent.clear()
  9303. self.ui.recent_projects.clear()
  9304. # Create menu items for projects
  9305. for recent in self.recent_projects:
  9306. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9307. if recent['kind'] == 'project':
  9308. try:
  9309. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9310. # Attach callback
  9311. o = make_callback(openers[recent["kind"]], recent['filename'])
  9312. action.triggered.connect(o)
  9313. self.ui.recent_projects.addAction(action)
  9314. except KeyError:
  9315. App.log.error("Unsupported file type: %s" % recent["kind"])
  9316. # Last action in Recent Files menu is one that Clear the content
  9317. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9318. clear_action_proj.triggered.connect(reset_recent_projects)
  9319. self.ui.recent_projects.addSeparator()
  9320. self.ui.recent_projects.addAction(clear_action_proj)
  9321. # Create menu items for files
  9322. for recent in self.recent:
  9323. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9324. if recent['kind'] != 'project':
  9325. try:
  9326. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9327. # Attach callback
  9328. o = make_callback(openers[recent["kind"]], recent['filename'])
  9329. action.triggered.connect(o)
  9330. self.ui.recent.addAction(action)
  9331. except KeyError:
  9332. App.log.error("Unsupported file type: %s" % recent["kind"])
  9333. # Last action in Recent Files menu is one that Clear the content
  9334. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9335. clear_action.triggered.connect(reset_recent_files)
  9336. self.ui.recent.addSeparator()
  9337. self.ui.recent.addAction(clear_action)
  9338. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9339. # self.ui.menufilerecent.set_submenu(recent_menu)
  9340. # recent_menu.show_all()
  9341. # self.ui.recent.show()
  9342. self.log.debug("Recent items list has been populated.")
  9343. def setup_component_editor(self):
  9344. # label = QtWidgets.QLabel("Choose an item from Project")
  9345. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9346. sel_title = QtWidgets.QTextEdit(
  9347. _('<b>Shortcut Key List</b>'))
  9348. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9349. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9350. settings = QSettings("Open Source", "FlatCAM")
  9351. if settings.contains("notebook_font_size"):
  9352. fsize = settings.value('notebook_font_size', type=int)
  9353. else:
  9354. fsize = 12
  9355. tsize = fsize + int(fsize / 2)
  9356. # selected_text = (_('''
  9357. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9358. #
  9359. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9360. # The normal flow when working in FlatCAM is the following:</span></p>
  9361. #
  9362. # <ol>
  9363. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9364. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9365. # even dragging and dropping the files on the GUI.<br />
  9366. # <br />
  9367. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9368. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9369. # &nbsp;</li>
  9370. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9371. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9372. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9373. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9374. # <br />
  9375. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9376. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9377. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9378. # it even if it was out of focus.<br />
  9379. # <br />
  9380. # You can change the parameters in this screen and the flow direction is like this:<br />
  9381. # <br />
  9382. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9383. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9384. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9385. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9386. # </ol>
  9387. #
  9388. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9389. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9390. # <strong>F3</strong>.</span></p>
  9391. #
  9392. # ''').format(fsize=fsize, tsize=tsize))
  9393. selected_text = '''
  9394. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9395. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9396. {s1}</span></p>
  9397. <ol>
  9398. <li><span style="font-size:{fsize}px">{s2}<br />
  9399. <br />
  9400. {s3}</span><br />
  9401. &nbsp;</li>
  9402. <li><span style="font-size:{fsize}px">{s4}<br />
  9403. &nbsp;</li>
  9404. <br />
  9405. <li><span style="font-size:{fsize}px">{s5}<br />
  9406. &nbsp;</li>
  9407. <br />
  9408. <li><span style="font-size:{fsize}px">{s6}<br />
  9409. <br />
  9410. {s7}</span></li>
  9411. </ol>
  9412. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9413. '''.format(
  9414. title=_("Selected Tab - Choose an Item from Project Tab"),
  9415. subtitle=_("Details"),
  9416. s1=_("The normal flow when working in FlatCAM is the following:"),
  9417. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9418. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9419. "files on the GUI."),
  9420. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9421. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9422. "actions offered within the app."),
  9423. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9424. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9425. "SELECTED TAB will be updated with the object properties according to its kind: "
  9426. "Gerber, Excellon, Geometry or CNCJob object."),
  9427. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9428. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9429. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9430. "the SELECTED TAB and populate it even if it was out of focus."),
  9431. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9432. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9433. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9434. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9435. "(again, done in SELECTED TAB) --> Save GCode."),
  9436. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9437. "or through its own key shortcut: <b>F3</b>."),
  9438. tsize=tsize,
  9439. fsize=fsize
  9440. )
  9441. sel_title.setText(selected_text)
  9442. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9443. self.ui.selected_scroll_area.setWidget(sel_title)
  9444. def setup_obj_classes(self):
  9445. """
  9446. Sets up application specifics on the FlatCAMObj class.
  9447. :return: None
  9448. """
  9449. FlatCAMObj.app = self
  9450. ObjectCollection.app = self
  9451. Gerber.app = self
  9452. Excellon.app = self
  9453. Geometry.app = self
  9454. CNCjob.app = self
  9455. FCProcess.app = self
  9456. FCProcessContainer.app = self
  9457. def version_check(self):
  9458. """
  9459. Checks for the latest version of the program. Alerts the
  9460. user if theirs is outdated. This method is meant to be run
  9461. in a separate thread.
  9462. :return: None
  9463. """
  9464. self.log.debug("version_check()")
  9465. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9466. full_url = App.version_url + \
  9467. "?s=" + str(self.defaults['global_serial']) + \
  9468. "&v=" + str(self.version) + \
  9469. "&os=" + str(self.os) + \
  9470. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9471. else:
  9472. # no_stats dict; just so it won't break things on website
  9473. no_ststs_dict = {}
  9474. no_ststs_dict["global_ststs"] = {}
  9475. full_url = App.version_url + \
  9476. "?s=" + str(self.defaults['global_serial']) + \
  9477. "&v=" + str(self.version) + \
  9478. "&os=" + str(self.os) + \
  9479. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9480. App.log.debug("Checking for updates @ %s" % full_url)
  9481. # ## Get the data
  9482. try:
  9483. f = urllib.request.urlopen(full_url)
  9484. except:
  9485. # App.log.warning("Failed checking for latest version. Could not connect.")
  9486. self.log.warning("Failed checking for latest version. Could not connect.")
  9487. self.inform.emit('[WARNING_NOTCL] %s' %
  9488. _("Failed checking for latest version. Could not connect."))
  9489. return
  9490. try:
  9491. data = json.load(f)
  9492. except Exception as e:
  9493. App.log.error("Could not parse information about latest version.")
  9494. self.inform.emit('[ERROR_NOTCL] %s' %
  9495. _("Could not parse information about latest version."))
  9496. App.log.debug("json.load(): %s" % str(e))
  9497. f.close()
  9498. return
  9499. f.close()
  9500. # ## Latest version?
  9501. if self.version >= data["version"]:
  9502. App.log.debug("FlatCAM is up to date!")
  9503. self.inform.emit('[success] %s' %
  9504. _("FlatCAM is up to date!"))
  9505. return
  9506. App.log.debug("Newer version available.")
  9507. self.message.emit(
  9508. _("Newer Version Available"),
  9509. _("There is a newer version of FlatCAM available for download:\n\n") +
  9510. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9511. _("info")
  9512. )
  9513. def on_plotcanvas_setup(self, container=None):
  9514. """
  9515. This is doing the setup for the plot area (VisPy canvas)
  9516. :param container: widget where to install the canvas
  9517. :return: None
  9518. """
  9519. if container:
  9520. plot_container = container
  9521. else:
  9522. plot_container = self.ui.right_layout
  9523. if self.is_legacy is False:
  9524. self.plotcanvas = PlotCanvas(plot_container, self)
  9525. else:
  9526. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9527. # So it can receive key presses
  9528. self.plotcanvas.native.setFocus()
  9529. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9530. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9531. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9532. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9533. # Keys over plot enabled
  9534. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9535. if self.defaults['global_cursor_type'] == 'small':
  9536. self.app_cursor = self.plotcanvas.new_cursor()
  9537. else:
  9538. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9539. if self.ui.grid_snap_btn.isChecked():
  9540. self.app_cursor.enabled = True
  9541. else:
  9542. self.app_cursor.enabled = False
  9543. if self.is_legacy is False:
  9544. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9545. else:
  9546. # will use the default Matplotlib axes
  9547. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9548. def on_zoom_fit(self, event):
  9549. """
  9550. Callback for zoom-out request. This can be either from the corresponding
  9551. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9552. with axes limits from the geometry bounds of all objects.
  9553. :param event: Ignored.
  9554. :return: None
  9555. """
  9556. if self.is_legacy is False:
  9557. self.plotcanvas.fit_view()
  9558. else:
  9559. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9560. width = xmax - xmin
  9561. height = ymax - ymin
  9562. xmin -= 0.05 * width
  9563. xmax += 0.05 * width
  9564. ymin -= 0.05 * height
  9565. ymax += 0.05 * height
  9566. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9567. def on_zoom_in(self):
  9568. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9569. def on_zoom_out(self):
  9570. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9571. def disable_all_plots(self):
  9572. self.report_usage("disable_all_plots()")
  9573. self.disable_plots(self.collection.get_list())
  9574. self.inform.emit('[success] %s' %
  9575. _("All plots disabled."))
  9576. def disable_other_plots(self):
  9577. self.report_usage("disable_other_plots()")
  9578. self.disable_plots(self.collection.get_non_selected())
  9579. self.inform.emit('[success] %s' %
  9580. _("All non selected plots disabled."))
  9581. def enable_all_plots(self):
  9582. self.report_usage("enable_all_plots()")
  9583. self.enable_plots(self.collection.get_list())
  9584. self.inform.emit('[success] %s' %
  9585. _("All plots enabled."))
  9586. def on_enable_sel_plots(self):
  9587. log.debug("App.on_enable_sel_plot()")
  9588. object_list = self.collection.get_selected()
  9589. self.enable_plots(objects=object_list)
  9590. self.inform.emit('[success] %s' %
  9591. _("Selected plots enabled..."))
  9592. def on_disable_sel_plots(self):
  9593. log.debug("App.on_disable_sel_plot()")
  9594. # self.inform.emit(_("Disabling plots ..."))
  9595. object_list = self.collection.get_selected()
  9596. self.disable_plots(objects=object_list)
  9597. self.inform.emit('[success] %s' %
  9598. _("Selected plots disabled..."))
  9599. def enable_plots(self, objects):
  9600. """
  9601. Disables plots
  9602. :param objects: list of Objects to be enabled
  9603. :return:
  9604. """
  9605. log.debug("Enabling plots ...")
  9606. # self.inform.emit(_("Working ..."))
  9607. for obj in objects:
  9608. if obj.options['plot'] is False:
  9609. obj.options.set_change_callback(lambda x: None)
  9610. obj.options['plot'] = True
  9611. obj.options.set_change_callback(obj.on_options_change)
  9612. def worker_task(objects):
  9613. with self.proc_container.new(_("Enabling plots ...")):
  9614. for obj in objects:
  9615. # obj.options['plot'] = True
  9616. if isinstance(obj, FlatCAMCNCjob):
  9617. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9618. else:
  9619. obj.plot(visible=True)
  9620. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9621. # self.plots_updated.emit()
  9622. def disable_plots(self, objects):
  9623. """
  9624. Disables plots
  9625. :param objects: list of Objects to be disabled
  9626. :return:
  9627. """
  9628. # if no objects selected then do nothing
  9629. if not self.collection.get_selected():
  9630. return
  9631. log.debug("Disabling plots ...")
  9632. # self.inform.emit(_("Working ..."))
  9633. for obj in objects:
  9634. if obj.options['plot'] is True:
  9635. obj.options.set_change_callback(lambda x: None)
  9636. obj.options['plot'] = False
  9637. obj.options.set_change_callback(obj.on_options_change)
  9638. try:
  9639. self.delete_selection_shape()
  9640. except Exception as e:
  9641. log.debug("App.disable_plots() --> %s" % str(e))
  9642. # self.plots_updated.emit()
  9643. def worker_task(objects):
  9644. with self.proc_container.new(_("Disabling plots ...")):
  9645. for obj in objects:
  9646. # obj.options['plot'] = True
  9647. if isinstance(obj, FlatCAMCNCjob):
  9648. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9649. else:
  9650. obj.plot(visible=False)
  9651. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9652. def toggle_plots(self, objects):
  9653. """
  9654. Toggle plots visibility
  9655. :param objects: list of Objects for which to be toggled the visibility
  9656. :return:
  9657. """
  9658. # if no objects selected then do nothing
  9659. if not self.collection.get_selected():
  9660. return
  9661. log.debug("Toggling plots ...")
  9662. self.inform.emit(_("Working ..."))
  9663. for obj in objects:
  9664. if obj.options['plot'] is False:
  9665. obj.options['plot'] = True
  9666. else:
  9667. obj.options['plot'] = False
  9668. self.plots_updated.emit()
  9669. def clear_plots(self):
  9670. objects = self.collection.get_list()
  9671. for obj in objects:
  9672. obj.clear(obj == objects[-1])
  9673. # Clear pool to free memory
  9674. self.clear_pool()
  9675. def generate_cnc_job(self, objects):
  9676. self.report_usage("generate_cnc_job()")
  9677. # for obj in objects:
  9678. # obj.generatecncjob()
  9679. for obj in objects:
  9680. obj.on_generatecnc_button_click()
  9681. def save_project(self, filename, quit_action=False, silent=False):
  9682. """
  9683. Saves the current project to the specified file.
  9684. :param filename: Name of the file in which to save.
  9685. :type filename: str
  9686. :param quit_action: if the project saving will be followed by an app quit; boolean
  9687. :param silent: if True will not display status messages
  9688. :return: None
  9689. """
  9690. self.log.debug("save_project()")
  9691. self.save_in_progress = True
  9692. with self.proc_container.new(_("Saving FlatCAM Project")):
  9693. # Capture the latest changes
  9694. # Current object
  9695. try:
  9696. self.collection.get_active().read_form()
  9697. except:
  9698. self.log.debug("There was no active object")
  9699. pass
  9700. # Project options
  9701. self.options_read_form()
  9702. # Serialize the whole project
  9703. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9704. "options": self.options,
  9705. "version": self.version}
  9706. if self.defaults["global_save_compressed"] is True:
  9707. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9708. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9709. # # Write
  9710. f.write(g)
  9711. self.inform.emit('[success] %s: %s' %
  9712. (_("Project saved to"), filename))
  9713. else:
  9714. # Open file
  9715. try:
  9716. f = open(filename, 'w')
  9717. except IOError:
  9718. App.log.error("Failed to open file for saving: %s", filename)
  9719. return
  9720. # Write
  9721. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9722. f.close()
  9723. # verification of the saved project
  9724. # Open and parse
  9725. try:
  9726. saved_f = open(filename, 'r')
  9727. except IOError:
  9728. if silent is False:
  9729. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9730. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9731. )
  9732. return
  9733. try:
  9734. saved_d = json.load(saved_f, object_hook=dict2obj)
  9735. except:
  9736. if silent is False:
  9737. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9738. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9739. )
  9740. f.close()
  9741. return
  9742. saved_f.close()
  9743. if silent is False:
  9744. if 'version' in saved_d:
  9745. self.inform.emit('[success] %s: %s' %
  9746. (_("Project saved to"), filename))
  9747. else:
  9748. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9749. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9750. )
  9751. settings = QSettings("Open Source", "FlatCAM")
  9752. lock_state = self.ui.lock_action.isChecked()
  9753. settings.setValue('toolbar_lock', lock_state)
  9754. # This will write the setting to the platform specific storage.
  9755. del settings
  9756. # if quit:
  9757. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9758. # t.start()
  9759. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9760. def start_delayed_quit(self, delay, filename, should_quit=None):
  9761. """
  9762. :param delay: period of checking if project file size is more than zero; in seconds
  9763. :param filename: the name of the project file to be checked periodically for size more than zero
  9764. :param should_quit: if the task finished will be followed by an app quit; boolean
  9765. :return:
  9766. """
  9767. to_quit = should_quit
  9768. self.save_timer = QtCore.QTimer()
  9769. self.save_timer.setInterval(delay)
  9770. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9771. self.save_timer.start()
  9772. def check_project_file_size(self, filename, should_quit=None):
  9773. """
  9774. :param filename: the name of the project file to be checked periodically for size more than zero
  9775. :param should_quit: will quit the app if True; boolean
  9776. :return:
  9777. """
  9778. try:
  9779. if os.stat(filename).st_size > 0:
  9780. self.save_in_progress = False
  9781. self.save_timer.stop()
  9782. if should_quit:
  9783. self.app_quit.emit()
  9784. except Exception as e:
  9785. traceback.print_exc()
  9786. def on_plotarea_tab_closed(self, tab_idx):
  9787. widget = self.ui.plot_tab_area.widget(tab_idx)
  9788. if widget is not None:
  9789. print(widget.objectName())
  9790. if widget.objectName() == 'text_editor_tab':
  9791. print("aha")
  9792. widget.deleteLater()
  9793. self.ui.plot_tab_area.removeTab(tab_idx)
  9794. def on_options_app2project(self):
  9795. """
  9796. Callback for Options->Transfer Options->App=>Project. Copies options
  9797. from application defaults to project defaults.
  9798. :return: None
  9799. """
  9800. self.report_usage("on_options_app2project")
  9801. self.defaults_read_form()
  9802. self.options.update(self.defaults)
  9803. self.options_write_form()
  9804. def on_options_project2app(self):
  9805. """
  9806. Callback for Options->Transfer Options->Project=>App. Copies options
  9807. from project defaults to application defaults.
  9808. :return: None
  9809. """
  9810. self.report_usage("on_options_project2app")
  9811. self.options_read_form()
  9812. self.defaults.update(self.options)
  9813. self.defaults_write_form()
  9814. def on_options_project2object(self):
  9815. """
  9816. Callback for Options->Transfer Options->Project=>Object. Copies options
  9817. from project defaults to the currently selected object.
  9818. :return: None
  9819. """
  9820. self.report_usage("on_options_project2object")
  9821. self.options_read_form()
  9822. obj = self.collection.get_active()
  9823. if obj is None:
  9824. self.inform.emit('[WARNING_NOTCL] %s' %
  9825. _("No object selected."))
  9826. return
  9827. for option in self.options:
  9828. if option.find(obj.kind + "_") == 0:
  9829. oname = option[len(obj.kind) + 1:]
  9830. obj.options[oname] = self.options[option]
  9831. obj.to_form() # Update UI
  9832. def on_options_object2project(self):
  9833. """
  9834. Callback for Options->Transfer Options->Object=>Project. Copies options
  9835. from the currently selected object to project defaults.
  9836. :return: None
  9837. """
  9838. self.report_usage("on_options_object2project")
  9839. obj = self.collection.get_active()
  9840. if obj is None:
  9841. self.inform.emit('[WARNING_NOTCL] %s' %
  9842. _("No object selected."))
  9843. return
  9844. obj.read_form()
  9845. for option in obj.options:
  9846. if option in ['name']: # TODO: Handle this better...
  9847. continue
  9848. self.options[obj.kind + "_" + option] = obj.options[option]
  9849. self.options_write_form()
  9850. def on_options_object2app(self):
  9851. """
  9852. Callback for Options->Transfer Options->Object=>App. Copies options
  9853. from the currently selected object to application defaults.
  9854. :return: None
  9855. """
  9856. self.report_usage("on_options_object2app")
  9857. obj = self.collection.get_active()
  9858. if obj is None:
  9859. self.inform.emit('[WARNING_NOTCL] %s' %
  9860. _("No object selected."))
  9861. return
  9862. obj.read_form()
  9863. for option in obj.options:
  9864. if option in ['name']: # TODO: Handle this better...
  9865. continue
  9866. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9867. self.defaults_write_form()
  9868. def on_options_app2object(self):
  9869. """
  9870. Callback for Options->Transfer Options->App=>Object. Copies options
  9871. from application defaults to the currently selected object.
  9872. :return: None
  9873. """
  9874. self.report_usage("on_options_app2object")
  9875. self.defaults_read_form()
  9876. obj = self.collection.get_active()
  9877. if obj is None:
  9878. self.inform.emit('[WARNING_NOTCL] %s' %
  9879. _("No object selected."))
  9880. return
  9881. for option in self.defaults:
  9882. if option.find(obj.kind + "_") == 0:
  9883. oname = option[len(obj.kind) + 1:]
  9884. obj.options[oname] = self.defaults[option]
  9885. obj.to_form() # Update UI
  9886. class ArgsThread(QtCore.QObject):
  9887. open_signal = pyqtSignal(list)
  9888. start = pyqtSignal()
  9889. if sys.platform == 'win32':
  9890. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9891. else:
  9892. address = ('/tmp/testipc', 'AF_UNIX')
  9893. def __init__(self):
  9894. super(ArgsThread, self).__init__()
  9895. self.start.connect(self.run)
  9896. def my_loop(self, address):
  9897. try:
  9898. listener = Listener(*address)
  9899. while True:
  9900. conn = listener.accept()
  9901. self.serve(conn)
  9902. except socket.error as e:
  9903. conn = Client(*address)
  9904. conn.send(sys.argv)
  9905. conn.send('close')
  9906. # close the current instance only if there are args
  9907. if len(sys.argv) > 1:
  9908. sys.exit()
  9909. def serve(self, conn):
  9910. while True:
  9911. msg = conn.recv()
  9912. if msg == 'close':
  9913. break
  9914. self.open_signal.emit(msg)
  9915. conn.close()
  9916. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9917. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9918. @pyqtSlot()
  9919. def run(self):
  9920. self.my_loop(self.address)
  9921. class GracefulException(Exception):
  9922. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9923. def __init__(self):
  9924. super().__init__()
  9925. def __str__(self):
  9926. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  9927. # end of file