FlatCAMApp.py 329 KB

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